/
app.js
1497 lines (1405 loc) · 49.8 KB
/
app.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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Module dependencies.
*/
var express = require('express');
require("express-namespace");
var everyauth = require('everyauth'),
EventEmitter = require('events').EventEmitter;
var imports = require("./imports.js"),
twitter = require("./twitter.js");
var sanitizer = require('sanitizer');
var icalendar = require('icalendar');
var https = require('https');
var http = require('http');
form = require("express-form"),
filter = form.filter,
validate = form.validate;
var fs = require('fs');
// Reading command line options
var argv = require("optimist")
.options('c', {
alias: 'config',
default:'config.ini'}).argv;
// Reading configuration file
var config = require('iniparser').parseSync(argv.c);
var app = express();
var server;
if (config.https.key_file && config.https.certificate_file) {
server = https.createServer({key: fs.readFileSync(config.https.key_file), cert: fs.readFileSync(config.https.certificate_file)}, app);
} else {
server = http.createServer(app);
}
module.exports = app;
var emitter = new EventEmitter();
var mongoose = require('mongoose'),
db = mongoose.createConnection(config.mongo.host, config.mongo.dbname);
var People = require('./model.js').People(db);
var Organization = require('./model.js').Organization(db);
var Place = require('./model.js').Place(db);
var Event = require('./model.js').Event(db);
var Status = require('./model.js').StatusUpdate(db);
var TaxiFromAirport = require('./model.js').TaxiFromAirport(db);
var TaxiToAirport = require('./model.js').TaxiToAirport(db);
var TwitterSettings = require('./model.js').TwitterSettings(db);
var places = {};
// Authentication
// Session Store
var SessionMongoose = require("session-mongoose");
var mongooseSessionStore = new SessionMongoose({
url: "mongodb://" + config.mongo.host + '/' + config.authentication.session_db,
interval: 120000 // expiration check worker run interval in millisec (default: 60000)
});
everyauth.everymodule.moduleTimeout(40000);
everyauth.everymodule.findUserById( function (userId, callback) {
// is there anyone in the db yet?
People.count({}, function(err, count) {
if (!count) {
// No one in the db, we create a mock user to allow for import
callback(err, {'login': userId, 'given': 'Admin', 'family': 'Istrator', 'slug': 'admin'});
} else {
People.findOne({login: userId}, callback);
}
});
});
/* everyauth.everymodule
.performRedirect( function (res, location) {
res.redirect(location, 303);
});
*/
// Adapted from everyauth ldap module
everyauth.password
.logoutPath(config.hosting.basepath + '/logout')
.logoutRedirectPath(config.hosting.basepath + '/login')
.getLoginPath(config.hosting.basepath + '/login')
.postLoginPath(config.hosting.basepath + '/login') // Uri path that your login form POSTs to
.loginView('login.ejs')
.registerView('index.ejs') // @@@ need fixing
.registerLocals(function (req, res, done) {
var until = new Date();
if (req.query["until"]) {
until = parseDate(req.query.until);
}
var limit = 20;
if (until > 0) {
limit = 1000;
}
Status.find({})
.sort('-time')
.limit(limit)
.where('time').lte(until)
.populate('author', ['given', 'family', 'slug', 'picture_thumb'])
.exec(function(err, statusupdates) {
if (err) return done(err);
if (req.user) {
Event.count({"interested":req.user._id}, function(err, count) {
done(null, {statusupdates: statusupdates, scheduledEvents: count});
});
} else {
done(null, {statusupdates: statusupdates});
}
});
})
.loginLocals(function (req, res) {
if (req.query["redirectTo"]) {
req.session.redirectTo = req.query["redirectTo"];
}
})
//.loginSuccessRedirect(config.hosting.basepath + '/')
.respondToRegistrationSucceed( function (res, user, data) {
if (data.session.redirectTo) {
this.redirect(res, data.session.redirectTo)
} else {
this.redirect(res, config.hosting.basepath + '/');
}
})
.respondToLoginSucceed( function (res, user, data) {
console.log(user);
console.log(data.session);
console.log(data.session.redirectTo);
if (data.session.redirectTo && user) {
res.writeHead(303, {"Location":data.session.redirectTo});
data.session.redirectTo = null;
res.end();
} else if (user){
res.writeHead(303, {"Location": config.hosting.basepath + '/'});
res.end();
}
})
.authenticate( function (login, password) {
var promise = this.Promise();
var errors = [];
if (!login) errors.push('Missing login');
if (!password) errors.push('Missing password');
if (errors.length) return errors;
var ldap = require('./ldapauth');
// modified version of ldapauth that takes an additional scheme parameter available from https://github.com/dontcallmedom/node-ldapauth
console.log(config.ldap);
ldap.authenticate(config.ldap.scheme, config.ldap.host, parseInt(config.ldap.port),'uid=' + login + ',' + config.ldap.dn_realm , password, function(err, result) {
if (err) {
return promise.fail(err);
}
if (result === false) {
errors = ['Login failed.'];
return promise.fulfill(errors);
} else {
var user = {id: login};
// We'll use this to get data from WBS when importing registrants list
// @@@ move to import.js? use cleaner abstraction
app.set('w3c_auth', new Buffer(login + ':' + password).toString('base64'));
return promise.fulfill(user);
}
});
return promise;
})
.getRegisterPath(config.hosting.basepath + '/')
.postRegisterPath(config.hosting.basepath + '/')
.registerUser(function() {
return null;
});
// Configuration
app.configure(function(){
emitter.setMaxListeners(0);
app.use(express.logger());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('port', config.hosting.hostname.split(":")[2] ? config.hosting.hostname.split(":")[2] : 3000);
app.use(express.bodyParser());
app.use(config.hosting.basepath, express.static(__dirname + '/public', { maxAge: 86400000}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({store: mongooseSessionStore, secret:config.authentication.session_secret, cookie: {maxAge: new Date(Date.now() + (config.authentication.duration ? parseInt(config.authentication.duration,10) : 3600*24*1000)), path: config.hosting.basepath }}));
app.use(function(req, res, next) {
res.locals.messages= require('express-messages');
res.locals.url = require("url").parse(req.url).pathname;});
app.use(everyauth.middleware());
// Loading up list of places
Place.find({}).sort('name').exec( function(err, rooms) {
if (err) {
console.log("No room known in the system");
} else {
for (i in rooms) {
places[rooms[i].shortname] = rooms[i];
}
}
});
// Loading up list of twitter users
TwitterSettings.findOne(
{},
function(err, settings) {
// No twitter settings
if (err || !settings) {
console.log("No twitter settings found, won't get updates from Twitter");
} else {
if (!(settings.username && settings.password)) {
console.log("Incomplete twitter settings found, won't get updates from Twitter: " + JSON.stringify(settings));
} else {
app.set('twitter_auth', new Buffer(settings.username + ':' + settings.password).toString('base64'));
if (true) {
People.find({}, ['twitterAccount'], function(err, people) {
for (p in people) {
if (people[p].twitterAccount && people[p].twitterAccount.id) {
settings.ids.push(people[p].twitterAccount.id);
}
}
// defaulting to registered list of users
if (!settings.ids.length) {
if (settings.list && settings.list.owner && settings.list.slug) {
// load a list of users from Twitter
twitter.listTwitterIdsFromTwitterList(
settings.list.owner,
settings.list.slug,
function (ids) {
settings.ids = ids;
settings.save();
twitter.listenToTweets(emitter, settings.ids, app.set('twitter_auth'));
});
}
} else {
settings.save();
twitter.listenToTweets(emitter, settings.ids, app.set('twitter_auth'));
}
});
} else {
twitter.listenToTweets(emitter, settings.ids, app.set('twitter_auth'));
}
}
}
});
if (config.schedule.autocheckout && config.schedule.autocheckout.match(/[0-9][0-9][0-9][0-9]?/)) {
var now = new Date();
var then = new Date();
then.setUTCHours(parseInt(config.schedule.autocheckout, 10) / 100 - parseInt(config.schedule.timezone_offset, 10));
then.setUTCMinutes(parseInt(config.schedule.autocheckout, 10) % 100);
if (then < now) {
then.setUTCDate(now.getUTCDate() + 1);
}
setTimeout(function() {
autoCheckout();
setInterval(autoCheckout, 3600 * 24 * 1000);
}, then - now);
console.log("Setting auto checkout " + ((then - now) / 1000) + " seconds from now");
}
});
app.configure('test', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
//db = mongoose.connect('mongodb://localhost/tpac-test');
});
app.configure('development', function(){
everyauth.debug = true;
app.use(express.logger());
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.logger());
app.use(express.errorHandler());
app.set('port', 80);
});
// Error handling
app.use(function(err, req, res, next) {
console.error(err.stack);
res.send(500, 'Something broke!');
});
// update twitter search on registering new twitter id
emitter.on("twitterListChange", function (id) {
if (id) {
TwitterSettings.findOne(
{},
function(err, settings) {
var ids = settings.ids;
ids.push(id);
settings.ids = ids;
twitter.listenToTweets(emitter, ids, app.set('twitter_auth'));
settings.save();
}
);
}
});
// Record events as statusupdates
emitter.on("checkin", function(user, left, entered) {
var status = new Status({author: user, time: Date.now(), statusType: "checkin", contentHTML: (left && left.name ? " left <a href='" + sanitizer.escape(config.hosting.basepath) + "/locations/" + sanitizer.escape(left.shortname) + "'>" + sanitizer.escape(left.name) + "</a>" + (entered && entered.name ? " and " : "") : "") + (entered && entered.name ? " entered <a href='" + sanitizer.escape(config.hosting.basepath) + "/locations/" + sanitizer.escape(entered.shortname) + "'>" + sanitizer.escape(entered.name) + "</a>" : "")});
status.save();
});
emitter.on("newevent", function(event) {
var time = event.time;
if (time) {
time.setUTCHours(time.getUTCHours() + parseInt(config.schedule.timezone_offset, 10));
var status = new Status({author: event.proposedBy, time: Date.now(), statusType: "event", contentHTML: " scheduled a new ad-hoc event: " + sanitizer.escape(event.name) + " at " + sanitizer.escape(time) + " in <a href='" + sanitizer.escape(config.hosting.basepath + "/locations/" + event.room.shortname) + "'>" + sanitizer.escape(event.room.name) + "</a>"});
status.save();
}
});
emitter.on("newtwitteraccount", function(indiv) {
var status = new Status({author: indiv, time: Date.now(), statusType:"profile", contentHTML: "’s profile is now bound with the <a href='http://twitter.com/" + sanitizer.escape(indiv.twitterAccount.name) + "'>Twitter account " + sanitizer.escape(indiv.twitterAccount.name) + "</a>"});
status.save();
});
emitter.on("tweet", function(tweet) {
People.findOne(
{"twitterAccount.id":tweet.user.id},
function(err, indiv) {
if (indiv) {
var status = new Status({author: indiv, time: Date.now(), statusType: "tweet", contentHTML: /*indiv.given + " " + indiv.family + */" <a href='http://twitter.com/" + sanitizer.escape(indiv.twitterAccount.name) + '/status/' + sanitizer.escape(tweet.id_str) + "'>tweeted</a>: “" + sanitizer.escape(tweet.text) + "” as <a href='http://twitter.com/" + sanitizer.escape(indiv.twitterAccount.name) + "'>@" + sanitizer.escape(indiv.twitterAccount.name) + "</a>"});
status.save();
}
});
});
// Utility function
// Parses YYYYMMDDTHHmm into a Date object
function parseDate(datestring) {
console.log("parsing date " + datestring);
var ret = new Date();
ret.setUTCFullYear(datestring.substr(0,4));
ret.setUTCMonth(datestring.substr(4,2) - 1);
ret.setUTCDate( datestring.substr(6,2));
ret.setUTCHours(parseInt(datestring.substr(9,2), 10));
ret.setUTCMinutes(datestring.substr(11,2));
ret.setUTCSeconds(0);
ret.setUTCMilliseconds(0);
return ret;
};
function elapsedTime(time) {
var elapsedTime = (Date.now() - time) / 1000 ;
var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var months = ["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"];
var days = Math.floor(elapsedTime / 86400);
var hours = Math.floor((elapsedTime - (days*86400)) / 3600);
var minutes = Math.floor((elapsedTime - (days * 86400) - (hours * 3600)) / 60);
if (days > 7) {
return time.getDate() + ' ' + months[time.getMonth()] + ' ' + time.getFullYear();
} else if (days > 1) {
return weekDays[time.getDay()] + ' (' + days.toString() + ' days ago)';
} else if (days == 2) {
return '2 days ago';
} else if (days == 1) {
return 'yesterday';
} else if (hours > 1) {
return hours.toString() + ' hours ago';
} else if (hours == 1) {
return '1 hour ago';
} else {
return minutes.toString() + ' minute' + (minutes > 1 ? 's' : '') + ' ago';
}
}
function prepareEventsList(events) {
var days = [];
var timeslots = [];
var schedule = {};
for (var i in events) {
events[i].timeStart.setUTCHours(events[i].timeStart.getUTCHours() + parseInt(config.schedule.timezone_offset, 10));
events[i].timeEnd.setUTCHours(events[i].timeEnd.getUTCHours() + parseInt(config.schedule.timezone_offset, 10));
var day = events[i].timeStart.toDateString();
var timeslot = {timeStart: events[i].timeStart , timeEnd: events[i].timeEnd};
if (!schedule[day]) {
days.push(day);
schedule[day] = {};
timeslots[day] = [];
}
if (!schedule[day][JSON.stringify(timeslot)]) {
schedule[day][JSON.stringify(timeslot)] = [];
timeslots[day].push(timeslot);
}
schedule[day][JSON.stringify(timeslot)].push(events[i]);
}
return [days, timeslots, schedule];
}
function addEvent(req, res, next, eventType, proposedBy) {
if (!req.body.name){
req.flash("error", "Missing event name");
next();
} else if (!req.body.day) {
req.flash("error", "Missing event day");
next();
} else if (!req.body.start) {
req.flash("error", "Missing event start time");
next();
} else if (!req.body.end) {
req.flash("error", "Missing event end time");
next();
}
// uuid generation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
var slug = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);});
var event = new Event(
{timeStart: parseDate(req.body.day + 'T' + String('0000' + (parseInt(req.body.start.replace(":",""), 10) - 100* parseInt(config.schedule.timezone_offset, 10))).slice(-4) + '00'),
timeEnd: parseDate(req.body.day + 'T' + String('0000' + (parseInt(req.body.end.replace(":",""), 10) - 100 * parseInt(config.schedule.timezone_offset, 10))).slice(-4) + '00'),
name: req.body.name,
presenters: req.body.presenters,
slug: slug,
confidentiality: req.body.confidentiality,
observers: req.body.observers,
eventType: eventType
});
if (proposedBy) {
event.proposedBy = proposedBy._id;
}
if (places[req.body.room]) {
event.room = places[req.body.room]._id;
} else {
req.flash('error', 'Failed to locate event “' + event.name + '” as it is set for a room with unknown shortname ' + req.body.room);
}
event.save(function (err) {
if (err) {
req.flash('error',err);
} else {
if (event.proposedBy) {
emitter.emit("newevent", event);
}
req.flash('info', req.body.name + ' successfully added to schedule') ;
}
next();
});
}
function autoCheckout() {
if (config.schedule.autocheckout) {
var now = new Date();
if (now.getUTCHours() + parseInt(config.schedule.timezone_offset, 10) > parseInt(config.schedule.autocheckout, 10) / 100 || (now.getUTCHours() + parseInt(config.schedule.timezone_offset, 10) == parseInt(config.schedule.autocheckout, 10) / 100 && now.getUTCMinutes() >= parseInt(config.schedule.autocheckout,10) % 100)) {
People.find({"lastKnownPosition.shortname": {$ne: null}}, ["lastKnownPosition"], function(err, people) {
if (err) {
console.log("autocheckout query error: " + err);
} else {
for (p in people) {
var indiv = people[p];
indiv.lastKnownPosition = { shortname: null, name:null, time: Date.now()};
indiv.save(function(err) {
if (err) {
console.log("autocheckout error: " + err);
}
});
}
}
});
}
}
}
// Routes
// Would be better in a post(/.*/) route but that breaks with express-namespace
// cf https://github.com/visionmedia/express-namespace/issues/5
function setFormatOutput(req) {
// if the _format parameter is set, we set req.outputFormat
if (req.body && req.body._format) {
req.outputFormat = req.body._format;
}
}
app.namespace(config.hosting.basepath, function(){
app.get('/', function(req, res){
// skipped by middleware at this point, need fixing @@@
People.count({}, function(err, count) {
if (!count) {
// no user, need to import data
if (! req.loggedIn) {
return res.redirect(everyauth.password.getLoginPath());
} else {
// Import basic data: people and rooms
imports.importUserList(app.set("w3c_auth"), function(success, info, errors) {
req.flash("info", "First run, importing registrants list");
if (success) success.forEach(function(i) { req.flash('success',i);});
if (info) info.forEach(function(i) { req.flash('info',i);});
if (errors) errors.forEach(function(i) { req.flash('error',i);});
res.render('index');
});
}
} else {
console.log("hello world");
res.render('index');
}
});
});
app.get('/about', function(req, res){
res.render('about', {locals: {title: 'About W3Connect'}});
});
app.post('/admin/', function(req, res, next){
if (! req.loggedIn) {
return res.redirect(everyauth.password.getLoginPath());
}
var isAdmin = new RegExp("^" + config.admin.login.replace(",","|") + "$");
if (!isAdmin.test(req.user.login)) {
return res.render("403");
}
if (req.body.peopleUpdate !== undefined) {
if (!app.set("w3c_auth")) {
// in case user logged in a previous session
// should find how to logout?
return res.redirect(everyauth.password.getLoginPath());
}
imports.importUserList(app.set("w3c_auth"), function(success, info, errors) {
if (success) success.forEach(function(i) { req.flash('success',i);});
if (info) info.forEach(function(i) { req.flash('info',i);});
if (errors) errors.forEach(function(i) { req.flash('error',i);});
next();
});
} else if (req.body.registrationUpdate !== undefined) {
imports.importRegistrationData(app.set("w3c_auth"), function(success, info, errors) {
if (success) success.forEach(function(i) { req.flash('success',i);});
if (info) info.forEach(function(i) { req.flash('info',i);});
if (errors) errors.forEach(function(i) { req.flash('error',i);});
next();
});
} else if (req.body.clearInterested !== undefined) {
var counter = 0;
Event.find(
{},
function(err, events) {
for (e in events) {
var event = events[e];
event.interested = [];
event.save(
function(err) {
counter++;
if (counter == events.length) {
req.flash("info", "Cleared");
next();
}
});
}
});
} else if (req.body.placeAdd !== undefined) {
var place = new Place();
place.shortname = req.body.shortname;
place.name = req.body.name;
place.save(
function(err) {
if (err) {
req.flash("error", "Error while adding new place: " + err);
} else {
req.flash("success", "New place added: " + p.name);
}
next();
}
);
} else if (req.body.placesUpdate !== undefined) {
var url = require("url").parse(config.map.rooms_json);
var http_client;
if (url.protocol == "http:") {
http_client = http;
} else if (url.protocol == "https:") {
http_client = https;
} else {
req.flash("error", "Unrecognized protocol for room descriptions: " + config.map.rooms_json);
next();
}
if (http_client) {
var request = http_client.get({host: url.hostname, port: url.port , path: url.pathname + (url.search ? url.search : '') + (url.hash ? url.hash : '')}, function (response) {
response.setEncoding('utf8');
var placesJSON = "", placesData;
response.on('data', function (chunk) {
placesJSON = placesJSON + chunk;
});
response.on('end', function () {
Place.find({}).remove();
placesData = JSON.parse(placesJSON);
for (i in placesData) {
var p = new Place(placesData[i]);
var counter = 0;
var addCounter = 0;
p.save(function (err) {
counter++;
if (err) {
req.flash('error',err);
} else {
addCounter++;
}
if (counter == placesData.length) {
next();
}
});
}
});
});
}
} else if (req.body.twitterSetting !== undefined) {
if (!req.body.username) {
req.flash("error", "Missing Twitter username");
next();
} else if (!req.body.password) {
req.flash("error", "Missing Twitter password");
next();
}
TwitterSettings.findOne(
{},
function(err, settings) {
if (!settings) {
settings = new TwitterSettings();
}
settings.username = req.body.username;
settings.password = req.body.password;
settings.save(function(err) {
if (err) {
req.flash("error", "Saving Twitter settings failed with error " + err);
} else {
req.flash("success", "Successfully saved Twitter settings");
}
next();
});
});
} else if (req.body.autocheckout) {
autoCheckout();
req.flash("success", "Autocheckout triggered");
next();
} else {
next();
}
});
app.all('/admin/', function(req, res){
res.render('admin/index', {locals: { title: 'Administration'}});
});
app.post('/people/profile/:id.:format?', function(req, res, next){
setFormatOutput(req);
if (! req.loggedIn) {
return res.redirect(everyauth.password.getLoginPath());
} else {
if (req.body.updateProfile !== undefined && req.body.twitter && req.user.slug == req.params.id) {
twitterAccount = req.body.twitter.replace(/^@/, '');
twitter.getTwitterId(twitterAccount, function(err, id) {
if (err) {
req.flash("error", err);
next();
} else {
People.findOne({slug: req.params.id}).exec( function(err, indiv) {
if (err) {
next();
} else {
indiv.twitterAccount = {"name": twitterAccount, id: id};
indiv.save(function(err) {
emitter.emit("newtwitteraccount", indiv);
// re-start twitter listener
emitter.emit("twitterListChange", id);
if (!err) {
req.flash("success", "Successfully added your twitter account");
} else {
req.flash("error", "Failed to add your twitter account: " + err);
}
next();
});
}
});
}
});
} else {
next();
}
}
});
app.all('/people/profile/:id.:format?', function(req, res, next){
People.findOne({slug: req.params.id}).populate('affiliation', ['slug', 'name']).exec( function(err, indiv) {
if (indiv) {
Event.find({})
.populate('proposedBy')
.populate('room', ['name'])
//.$where('RegExp("^" + this.interested.join("|") + "$").test(' + indiv._id + ')')
.sort('timeStart')
.exec(function(err, events) {
var days, timeslots, schedule;
var userEvents = [];
if (events) {
for (var i = 0; i < events.length ; i++) {
var isInterested = new RegExp("^" + events[i].interested.join("|") + "$");
if (isInterested.test(indiv._id)) {
userEvents.push(events[i]);
}
}
var data = prepareEventsList(userEvents);
days = data[0];
timeslots = data[1];
schedule = data[2];
}
Status.find({"author": indiv})
.sort("-time")
.limit(20)
.exec(function(err, statusupdates) {
switch (req.params.format) {
// When json, generate suitable data
case 'json':
res.send(indiv);
break;
case 'ics':
res.header("Content-Type", "text/calendar");
var ical = new icalendar.iCalendar();
for (var i = 0 ; i < userEvents.length ; i++) {
var event = userEvents[i];
var icalEv = new icalendar.VEvent(event.slug);
icalEv.setSummary(event.name);
if (event.room) {
icalEv.addProperty('LOCATION', event.room.name);
}
icalEv.setDate(event.timeStart.setUTCHours(event.timeStart.getUTCHours() - parseInt(config.schedule.timezone_offset, 10)),new Date(event.timeEnd.setUTCHours(event.timeEnd.getUTCHours() - parseInt(config.schedule.timezone_offset, 10))));
ical.addComponent(icalEv);
}
res.send(ical.toString());
break;
default:
res.render('people/indiv.ejs', { locals: { indiv: indiv, title: indiv.given + ' ' + indiv.family, days: days, timeslots: timeslots, schedule:schedule, statusupdates: statusupdates }});
}
});
});
} else {
next();
}
});
});
app.get('/locations.:format?', function(req, res) {
var counter=0;
if (Object.keys(places).length == 0) {
res.render('locations/index.ejs', { locals: { places: places, title: 'Rooms'}});
return;
}
for (var p in places) {
People.find({"lastKnownPosition.shortname": places[p].shortname}, ['slug', 'given', 'family', 'picture_thumb'], (function(place) { return function(err, people) {
counter++;
place.checkedin = people;
if (counter==Object.keys(places).length) {
switch (req.params.format) {
// When json, generate suitable data
case 'json':
res.send(places);
break;
default:
res.render('locations/index.ejs', { locals: { places: places, title: 'Rooms'}});
}
}
};})(places[p]));
}
});
app.get('/locations/stream', function(req, res) {
res.setHeader("Content-Type", 'text/event-stream');
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.writeHead(200);
setInterval(function() { res.write(":\n"); }, 30000);
emitter.on("checkin", function(user, left, entered) {
res.write("data: " + JSON.stringify({"user": user, "left": left, "entered": entered, "you": (req.user && JSON.stringify(user._id) == JSON.stringify(req.user._id))}) + "\n\n");
});
emitter.on("tweet", function(tweet) {
People.findOne(
{"twitterAccount.id":tweet.user.id},
["lastKnownPosition"],
function(err, indiv) {
res.write("event: tweet\n");
tweet.position = "";
if (indiv && indiv.lastKnownPosition && indiv.lastKnownPosition.shortname) {
tweet.position = indiv.lastKnownPosition.shortname;
}
res.write("data: " + JSON.stringify(tweet) + "\n\n");
});
});
});
function userCheckin(req, res, next, place) {
// the user is already checked in in that place
var actionNeeded = true;
if (req.user.lastKnownPosition.shortname == place.shortname) {
if (req.body.checkin !== undefined) {
actionNeeded = false;
switch (req.outputFormat) {
case "json":
res.send(JSON.stringify({success: "Already checked in at " + place.name}));
break;
default:
req.flash('info', "You’re already checked in at " + place.name);
if (next) next();
}
}
} else {
if (req.body.checkout !== undefined) {
actionNeeded = false;
switch (req.outputFormat) {
case "json":
res.send(JSON.stringify({error: "You’re not checked in at " + place.name + ", so you can’t checkout from it"}));
break;
default:
req.flash('info', "You’re not checked in at " + place.name + ", so you can’t checkout from it");
if (next) next();
}
}
}
if (actionNeeded) {
var indiv = req.user ;
var prevPosition = {shortname: indiv.lastKnownPosition.shortname,
name: indiv.lastKnownPosition.name,
time: indiv.lastKnownPosition.time};
var newPosition = {shortname: null, name: null, time: Date.now()};
if (req.body.checkin !== undefined) {
newPosition.shortname = place.shortname;
newPosition.name = place.name;
}
indiv.lastKnownPosition = newPosition;
indiv.save(function(err) {
req.flash('error',err);
if (!err) {
emitter.emit("checkin", req.user, prevPosition, newPosition);
}
switch (req.outputFormat) {
case 'json':
if (!err) {
res.send(JSON.stringify({success: (req.body.checkin !== undefined ? 'Checked in at ' + newPosition.name : "Checked out")}));
} else {
res.send(JSON.stringify({error: err}));
}
break;
default:
if (!err) {
req.flash('info', (req.body.checkin !== undefined ? 'Checked in at ' + newPosition.name : "Checked out"));
} else {
req.flash('error', err);
}
if (next) next();
}
});
}
}
app.post('/locations/:id.:format?', function(req, res, next) {
setFormatOutput(req);
if (! req.loggedIn) {
req.session.redirectTo = '/locations/' + req.params.id;
return res.redirect(everyauth.password.getLoginPath());
}
var place = places[req.params.id];
if (place) {
if ((req.body.checkin !== undefined || req.body.checkout !== undefined) && req.user) {
userCheckin(req, res, next, place)
} else {
next();
}
} else {
next();
}
});
app.all('/locations/:id.:format?', function(req, res) {
var place = places[req.params.id];
if (place) {
People.find({"lastKnownPosition.shortname": place.shortname}, ['slug', 'given', 'family', 'picture_thumb', 'lastKnownPosition'])
.exec(function(err, people) {
people.sort(function (a,b) { return (a.lastKnownPosition.time > b.lastKnownPosition.time ? -1 : (b.lastKnownPosition.time > a.lastKnownPosition.time ? 1 : 0));});
var current = new Date();
if (req.query.datetime) {
current = parseDate(req.query.datetime);
if (isNaN(current.getTime())) {
current = new Date();
}
}
Event.findOne({"room": place._id})
.where('timeStart').lte(current)
.where('timeEnd').gte(current)
.populate('proposedBy')
.exec(
function(err, event) {
switch (req.params.format) {
// When json, generate suitable data
case 'json':
var placeData = place.toObject();
placeData.checkedin = people.map(function(x) { return x.toObject();});
res.send(placeData);
break;
default:
var render = function () {
res.render('locations/place.ejs', { locals: { place: place, people: people, title: place.name, places:places, event: event}});
};
// auto-check-in if nfc is set in the query string
if (req.loggedIn && req.query["nfc"] === '') {
req.body.checkin = true;
userCheckin(req, res, render, place)
} else {
render();
}
}
});
});
} else {
res.render('locations/unknown.ejs', {locals: { shortname: req.params.id, title: 'Unknown location'}});
}
});
app.post("/locations/:id/admin", function(req,res, next) {
if (req.body.placeUpdate !== undefined) {
if (!req.body.name) {
req.flash("error", "Missing name of room to update");
next();
}
var place = places[req.params.id];
if (!place) {
req.flash("error", "No room found with shortname " + req.params.id);
next();
}
place.name = req.body.name;
place.save(
function(err) {
if (err) {
req.flash("error", err);
} else {
req.flash("success", "Room successfully updated");
}
next();
});
} else {
next();
}
});
app.all("/locations/:id/admin", function(req,res, next) {
var place = places[req.params.id];
if (place) {
res.render("locations/admin.ejs", {locals: {place: place}});
} else {
next();
}
});
app.get('/people/:letter?.:format?', function (req, res, next){
var letter = req.params.letter;
if (!letter) {
letter = "a";
}
if (!(letter=='all' || letter.match(/^.$/))) {
next();
}
var people = People.find({})
.exec(function (err, people) {
var activeLetters = {};
var letterPeople = [];
people.sort(function (a,b) { return a.family.toLowerCase().localeCompare(b.family.toLowerCase());});
for (var p in people) {
activeLetters[people[p].family[0].toUpperCase()]++;
if (letter != 'all' && people[p].family[0].toLowerCase() == letter.toLowerCase()) {
letterPeople.push(people[p]);
}
}
if (letter == 'all') {
letterPeople = people;
}
switch (req.params.format) {
// When json, generate suitable data
case 'json':
res.send(letterPeople);
break;
default:
res.render('people/index.ejs', { locals: { activeLetters: activeLetters, letter: letter, people: letterPeople, title: 'People — ' + letter}});
}
});
});
app.get('/orgs.:format?', function (req, res){
var orgs = Organization.find({})
.populate('employees', ['login'])
.exec( function (err, orgs) {
orgs.sort(function (a,b) { return (a.name > b.name ? 1 : (b.name > a.name ? -1 : 0));});