-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
166 lines (146 loc) · 4.98 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
var url = require('url'),
http = require('http'),
https = require('https'),
fs = require('fs'),
qs = require('querystring'),
express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
mongo = require('mongodb').MongoClient,
_ = require('underscore');
// Set up our mongo data and decorator
var msgs = null;
function decorateMessage(msg) {
msg.timestamp = new Date();
return msg;
}
// Load config defaults from JSON file.
// Environment variables override defaults.
function loadConfig() {
var config = JSON.parse(fs.readFileSync(__dirname+ '/config.json', 'utf-8'));
for (var i in config) {
config[i] = process.env[i.toUpperCase()] || config[i];
}
console.log('Configuration');
console.log(config);
return config;
}
var config = loadConfig();
function authenticate(code, cb) {
var data = qs.stringify({
client_id: config.oauth_client_id,
client_secret: config.oauth_client_secret,
code: code
});
var reqOptions = {
host: config.oauth_host,
port: config.oauth_port,
path: config.oauth_path,
method: config.oauth_method,
headers: { 'content-length': data.length }
};
var body = "";
var req = https.request(reqOptions, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) { body += chunk; });
res.on('end', function() {
cb(null, qs.parse(body).access_token);
});
});
req.write(data);
req.end();
req.on('error', function(e) { cb(e.message); });
}
// Convenience for allowing CORS on routes - GET only
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get('/authenticate/:code', function(req, res) {
console.log('authenticating code:' + req.params.code);
authenticate(req.params.code, function(err, token) {
var result = err || !token ? {"error": "bad_code"} : { "token": token };
console.log(result);
res.json(result);
});
});
app.use(express.static(__dirname + '/public'));
//mongo.connect("mongodb://localhost:27017/learnlocity", function(err, db) {
mongo.connect("mongodb://$admin:ixl101#[email protected]:27748/coderdojolearnlocity", function(err, db) {
msgs = db.collection('msg');
io.configure(function() {
io.set('transports', ['websocket']);
io.set('log level', 5)
});
io.sockets.on('connection', function(socket) {
socket.on('msg', function(msg) {
var decoratedMessage = decorateMessage(msg);
socket.broadcast.emit("msg", decoratedMessage);
msgs.insert(decoratedMessage, function(err, result) {
if (err) {
console.log('Error:');
console.log(err);
}
});
});
socket.on('query', function(query, callback) {
console.log('query is:');
console.log(query);
msgs.find(query).toArray(function(err, items) {
if (err) {
console.log('Error:');
console.log(err);
} else {
callback(items);
}
});
});
socket.on('queryMissionUsersNow', function(mission, callback) {
console.log('queryMissionUsersNow is:');
console.log(mission);
var now = new Date();
var since = new Date(now - 1*60*1000);
// TODO: better to aggregate or reduce in mongo than in underscore
var query = {
$or: [
{
mission: mission,
type: 'mission.join',
timestamp:{ $gte:since}
},
{
mission: mission,
type: 'mission.leave',
timestamp:{ $gte:since}
}
]
};
msgs.find(query).sort({timestamp:-1}).toArray(function(err, items) {
if (err) {
console.log('Error:');
console.log(err);
} else {
var userGroups = _.groupBy(items, function(item) { return item.userName; });
var mostRecents = _.map(userGroups, function(item) { return item[0] });
var joins = _.chain(mostRecents).where({type:'mission.join'}).pluck('userName').value();
var leaves = _.chain(mostRecents).where({type:'mission.leave'}).pluck('userName').value();
var keeps = _.difference(joins, leaves);
var missionUsersNow = _.filter(mostRecents, function(item) { return _.contains(keeps, item.userName) } );
var response = {
mission: mission,
items: missionUsersNow
};
callback(response);
}
});
});
});
});
var port = process.env.PORT || config.port || 80;
server.listen(port, null, function (err) {
console.log('Learnlocity server listening at your service: http://localhost:' + port);
});