-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
268 lines (237 loc) · 8.16 KB
/
Copy pathapp.js
File metadata and controls
268 lines (237 loc) · 8.16 KB
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
var http = require('http'); //Used for server creation
var express = require('express'); //Used for express
var fs = require('fs'); //Used for JSON file creation
var twitter = require('ntwitter'); //Used for getting twitter stream
var mongo = require('mongodb'); //Host: localhost, Port: 27017
var mongojs = require('mongojs'); //Emulates Mongo API
var databaseUrl = 'example';
var collections = ["tweetsCollection"]
var db = mongojs(databaseUrl, collections);
var app = express();
//Twitter API token
var twit = new twitter({
consumer_key: 'lPsEG5TceJEaKNb85OvQ',
consumer_secret: '6WkHzyehZrNUi9abp9AFyXD24qCILTyTiu53klvQ',
access_token_key: '2372874818-ycpFnKhqX1ldx72ZVybJXwgl5XmiTBrGfpjNbH4',
access_token_secret: 'iULhFJcOB0naq9gt7TY0T5Av3VbBqs9ZqD0v1D8kwZa4d'
});
var tweetCounter = 0;
var databaseTweets; //Will store tweets pulled from database
var tweets = []; //Stores tweets pulled from stream
var tweetCap = 15; //Number of tweets to get from stream
app.use(express.static(__dirname + '/resources'));
//Start button page
app.get('/', function(req, res) {
res.sendfile(__dirname + '/resources/start.html');
});
//Button panel page
app.post('/start', function(req, res) {
//Clear any existing documents in database
db.tweetsCollection.remove();
//Stream twitter and put into mongoDB
getTwitterStream(false);
//Show tweet visualization!
res.sendfile(__dirname + '/resources/lab8.html');
});
//If user clicks Build JSON File button
app.post('/buildJSON', function(req, res) {
db.tweetsCollection.remove(); //Remove previous documents in db
res.sendfile(__dirname + '/resources/lab8.html');
getTwitterStream(true);
});
//If user clicks Convert to CSV button
app.post('/convert', function(req, res) {
res.sendfile(__dirname + '/resources/lab8.html');
JSONtoCSV();
});
//If user clicks Build Database button
app.post('/buildDB', function(req,res) {
db.tweetsCollection.remove(); //Remove previous documents in db
res.sendfile(__dirname + '/resources/lab8.html');
getTwitterStream(false);
});
//If user clicks Read Tweets button
app.post('/read', function(req,res) {
//Pull all tweets from database
db.tweetsCollection.find(function(err, docs) {
var buffer = [];
buffer[0] = new Buffer('var tweetsToDisplay = ', 'utf-8'); //Treat data like a variable
buffer[1] = new Buffer(JSON.stringify(docs, null, '\t'), 'utf-8'); //Add documents from database
var combinedBuffer = Buffer.concat(buffer);
fs.writeFileSync('resources/databaseTweets.js', combinedBuffer); //Write to a file in same directory
//as displayTweets.html
});
res.sendfile(__dirname + '/resources/displayTweets.html');
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
console.log('Listening on port %d', server.address().port);
/*Looks at twitter stream, grabs relevant tweets, and inserts into mongoDB or JSON file depending on bool parameter*/
function getTwitterStream(isJSON)
{
console.log('getTwitterStream');
tweets = [];
tweetCounter = 0;
twit.stream('statuses/sample', function(stream)
{
stream.on('data', function(data)
{
if(isJSON) //Generating JSON file
{
fs.open('tweets.json', 'a', null, function(error, fd)
{
if(error)
{
console.log(error);
}
else
{
tweets[tweetCounter] = data;
//Stringify for pretty JSON formatting
buffer = new Buffer(JSON.stringify(data, null, '\t'), 'utf-8');
fs.writeSync(fd, buffer, null, buffer.length, null); //Write to the file
fs.closeSync(fd)
console.log('Writing JSON - tweet #' + tweetCounter);
tweetCounter++;
//Limit file to a specific number of tweets
if(tweetCounter > tweetCap)
{
console.log('Done writing.');
tweetCounter = 0;
stream.destroy();
}
}
});
}
else
{
tweets[tweetCounter] = data;
console.log('Inserting to database - tweet #' + tweetCounter);
tweetCounter++;
if(tweetCounter > tweetCap)
{
console.log('Over limit');
for(var i = 0; i < tweets.length; i++)
{
db.tweetsCollection.insert({
"id" : tweets[i].id,
"created_at" : tweets[i].created_at,
"text" : tweets[i].text,
"user_id" : tweets[i].user.id,
"user_name" : tweets[i].user.name,
"screen_name" : tweets[i].user.screen_name,
"location" : tweets[i].user.location,
"followers_count" : tweets[i].user.followers_count,
"friends_count" : tweets[i].user.friends_count,
"user_created_at" : tweets[i].user.user_created_at,
"time_zone" : tweets[i].user.time_zone,
"profile_background_color" : tweets[i].profile_background_color,
"profile_image_url" : tweets[i].user.profile_image_url,
"geo" : tweets[i].geo,
"coordinates" : tweets[i].coordinates,
"place" : tweets[i].place,
"hashtags" : tweets[i].entities.hashtags,
"lang" : tweets[i].lang
}
, function(err, doc) {
if(err)
{
console.log('Error with building database');
console.log(err);
}
});
}
console.log('Done writing to database');
tweetCounter = 0;
stream.destroy();
}
}
});
stream.on('end', function(res) {
});
stream.on('destroy', function(res) {
console.log('Stream destroyed');
getMongoTweets();
});
});
}
/*Pulls tweets stored in mongo database and writes them to a JS file*/
function getMongoTweets()
{
db.tweetsCollection.find().toArray(function(err, docs) {
//If nothing is stored in the database, show error message in browser
if(docs == null)
{
io.sockets.on('connection', function(socket) {
socket.emit('noDB');
});
}
else
{
console.log('Creating databaseTweets.js');
var buffer = [];
buffer[0] = new Buffer('var tweetsToDisplay = ', 'utf-8'); //Treat data like a javascript variable
buffer[1] = new Buffer(JSON.stringify(docs, null, '\t'), 'utf-8'); //Add documents from database
var combinedBuffer = Buffer.concat(buffer);
fs.writeFileSync('resources/databaseTweets.js', combinedBuffer); //Write to a file in same directory
} //as displayTweets.html
});
}
/*Converts JSON file filled with tweet data to CSV file*/
function JSONtoCSV()
{
//Check if JSON file exists before trying to convert
if(fs.existsSync('tweets.json'))
{
var headerRow = "created_at,id,text,user_id,user_name,user_screen_name,user_location,user_followers_count,user_friends_count,user_created_at,user_time_zone,user_profile_background_color,user_profile_image_url,geo,coordinates,place\r\n";
fs.open('tweets.csv', 'w', null, function(error, fd)
{
if(error)
{
console.log(error);
}
else
{
buffer = new Buffer(headerRow, 'utf-8');
fs.writeSync(fd, buffer, null, buffer.length, null);
//Loop through tweets and extract data specific data
for(var i = 0; i < tweets.length; i++)
{
console.log('Converting tweet #' + i);
var line = '';
line += "\"" + tweets[i].created_at + "\",";
line += tweets[i].id + ',';
line += "\"" + tweets[i].text + "\",";
line += tweets[i].user.id + ',';
line += "\"" + tweets[i].user.name + "\",";
line += "\"" + tweets[i].user.screen_name + "\",";
line += "\"" + tweets[i].user.location + "\",";
line += tweets[i].user.followers_count + ',';
line += tweets[i].user.friends_count + ',';
line += "\"" + tweets[i].user.created_at + "\",";
line += tweets[i].user.time_zone + ',';
line += tweets[i].user.profile_background_color + ',';
line += tweets[i].user.profile_image_url + ',';
line += tweets[i].geo + ',';
line += tweets[i].coordinates + ',';
line += tweets[i].place + ',';
line += "\r\n";
buffer = new Buffer(line, 'utf-8');
fs.writeSync(fd, buffer, null, buffer.length, null);
}
fs.closeSync(fd);
console.log('Done converting.');
io.sockets.on('connection', function(socket) {
socket.emit('convert_done');
});
}
});
}
else
{
io.sockets.on('connection', function(socket) {
socket.emit('noJSONfile');
});
}
}