-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·235 lines (205 loc) · 6.48 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
var myConsumerSecret="j9wmVOLlSUrRlvucX19oYvhFrWBFnePBqewABrjmbcU";
//var myConsumerSecret goes up here
/**
* Module dependencies.
*/
var express=require('express');
var http=require('http');
var path=require('path');
var util=require('util');
var OAuth=require('oauth').OAuth;
var twitter=require('ntwitter');
var io=require('socket.io').listen(8081, {log: false});
var sentiment=require('sentiment');
var TweetsProvider=require('./mongoConnector.js').TweetsProvider;
var async=require('async');
var fs=require('fs');
var app=express();
var mongoGrab=new TweetsProvider('127.0.0.1', 27017);
//Custom middleware to replace body parser
function rawBody(req, res, next) {
req.setEncoding('utf8');
req.rawBody = '';
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function(){
next();
});
}
// Environment setup
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/app');
app.set('view engine', 'ejs');
//app.set('view engine', 'jade');
//app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(rawBody);
//app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('anotherSecret'));
app.use(express.session());
app.use(app.router);
app.use(express.session({secret:"aSecret"}));
app.use(express.static(path.join(__dirname, 'app')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//Permit statically loaded pages
app.configure(function() {
app.use(express.static(__dirname + '/app'));
});
// Routes
app.post('/getTweets', function(req, res)
{
console.log("getTweets Requested\n");
//console.log("Body is: %j", req.rawBody);
if(req.session.oauth)
{
var twit=new twitter({
consumer_key: "jfy4Y6ucET5LZLXDTyncLw",
//Consumer secret goes here:
consumer_secret: myConsumerSecret,
access_token_key: req.session.oauth.access_token,
access_token_secret: req.session.oauth.access_token_secret
});
}
twit.verifyCredentials(function(err,data){
console.log(err, data);
});
var body=JSON.parse(req.rawBody);
twit.stream(
'statuses/filter',
{track:[body.data]},
function(stream) {
stream.on('data', function(data) {
//console.log(data.text);
//Calculate sentiment
sentiment(data.text, function(err, result){
data.sentiment=result.score;
console.log("Results:");
console.dir(result);
console.log(data.sentiment);
io.sockets.emit('newTweet', data)
});
});
});
});
app.post('/getQuiz', function(req, res){
console.log("Got that quiz");
var raw=JSON.parse(req.rawBody);
var query="{\"sentiment\": {\"$ne\": 0}}";
console.log(req.rawBody);
var mongoReq="{\"collection\":\"quiz"+raw.data+"\"}";
//var mongoReq="{\"collection\":\"riders\"}";
console.log(mongoReq);
query=JSON.parse(query);
mongoGrab.findAll(mongoReq, function(error, tweets){
//console.log("Found something: ", tweets);
var baseTime=tweets[0].time;
var baseNow=Date.now();
for(var i= 0; i<tweets.length; i++)
{
/*Emit each tweet to the caller on specified time
augmented by an offset of 50msec per tweet, to allow
the page to render at a reasonable rate */
(function(data, length,curr) {
setTimeout(function() {
io.sockets.emit('newTweet', data);
if(curr==length-1)
{
console.log("DONE THIS QUIZ");
io.sockets.emit('doneQuiz', {});
}
//}, data.time+(50*i)-baseTime);
}, (50*i));
})(tweets[i],tweets.length,i);
}
});
res.send("test");
});
app.post('/getQuizAve', function(req, res){
var raw=JSON.parse(req.rawBody);
var mongoReq="{\"collection\":\"quiz"+raw.data+"\"}";
//var mongoReq="{\"collection\":\"riders\"}";
mongoGrab.getAverage(mongoReq, function(error, averages){
console.log("got average");
io.sockets.emit('gotAverage', averages[0]);
});
});
app.post('/writeResults', function(req, res){
var raw=JSON.parse(req.rawBody);
fs.appendFile('answers.json', JSON.stringify(raw.data)+"\n", function (err) {
console.log(err);
});
res.send("Answers written.");
});
/********************TWITTER OAUTH****************************/
var oa=new OAuth(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"jfy4Y6ucET5LZLXDTyncLw",
//Consumer secret goes here:
myConsumerSecret,
"1.0",
"http://localhost:8080/auth/twitter/callback",
"HMAC-SHA1"
);
app.get('/auth/twitter', function(req, res){
oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
if(error)
{
console.log(error)
res.send('Log In Failed.');
}
else
{
req.session.oauth={};
req.session.oauth.token=oauth_token;
console.log('OAuth token:'+req.session.oauth.token);
req.session.oauth.token_secret=oauth_token_secret;
console.log('OAuth Token Secret:'+req.session.oauth.token_secret);
res.redirect('https://twitter.com/oauth/authenticate?oauth_token='+oauth_token);
}
});
});
app.get('/auth/twitter/callback', function(req, res, next){
if(req.session.oauth) {
req.session.oauth.verifier=req.query.oauth_verifier;
var oauth=req.session.oauth;
oa.getOAuthAccessToken(oauth.token,oauth.token_secret, oauth.verifier,
function(error, oauth_access_token, oauth_access_token_secret, results)
{
if(error){
console.log("Error in callback");
console.log(error);
res.send("Error in Twitter Callback on Log in.");
}
else
{
req.session.oauth.access_token=oauth_access_token;
req.session.oauth.access_token_secret=oauth_access_token_secret;
console.log("HERE'S THE RESULTS:")
console.log(results);
var twit=new twitter({
consumer_key: "jfy4Y6ucET5LZLXDTyncLw",
//Consumer secret goes here
consumer_secret: myConsumerSecret,
access_token_key: req.session.oauth.access_token,
access_token_secret: req.session.oauth.access_token_secret
});
twit.verifyCredentials(function(err, data){
console.log(err,data);
res.redirect('/');
})
}
});
} else
next(new Error("Something very wrong happened here."));
});
/******************END TWITTER OAUTH*******************************/
//Start our server
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});