-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp-working.js
807 lines (673 loc) · 20.3 KB
/
app-working.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
/**
*
*/
var amqp = require('amqplib');
var express = require('express')();
var app= require('http').Server(express);
//var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
var _ = require('underscore');
var wpimg = require('wikipedia-image');
// var config = require('./config');
// app.timeout = 0;// trying to fix a stupid error
app.listen(9001);
var startup_date = new Date();
var active_users = 0;
var temp_user_cnt = 0;
// var keyword_filter = "";
// var language_filter = "";
var processed_msg_cnt = 0;
// don't need the global filters_made
// var filters_made = [];
// DATA STRUCTURE ds[room]= {}
// vizs=[]
// filter={}
// filter.keyword
// filter.language
// filters_made=[]
var ds = [];
var rooms = [];
function showErr(e) {
console.error(e, e.stack);
}
function handler(req, res) {
res.writeHead(200);
res.end("");
}
io.sockets.setMaxListeners(0);
// SOCKET DETAILS
// Current socketnames in use:
// user_heartbeat
// active_user
// filter
// filter_keyword
// set_filter_keyword
// filter_lang
// set_filter_lang
// processed_messages;
// Hoses (Mappings from RabbitMQ)
// trends
// news
// twitter
// spinn3r
// wikipedia_revisions
// wikipedia_images
// twitter_delete
// twitter_delete_pulse
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/roomDB');
mongoose.Promise = global.Promise;
// notification if we connect successfully to the db or if a connection error
// occurs
var db = mongoose.connection;
//img paths
var imgPath0 = '\ms.png';
var imgPath1 = '\wikipediamap(resized).png';
var imgPath2 = '\cascades.png';
var imgPath3 = '\deletedtweets(resized).png';
db.on('error', console.error.bind(console, 'connection error:'));
// reference to the schema
var roomsSchema = mongoose.Schema({
roomID : Number,
roomName: String,
timeCreated : Date,
owner : String,
attached_vizs : Array,
// state of the room, if it's still visible
active : Boolean,
description : String,
stats : {
view_count : Number,
unique_participants : Array
}
// when the room becomes inactive
// time_archived: Date
}, {
// _id: false,
versionKey : false
});
// compiling our schema into a Model
var Room = mongoose.model('Room', roomsSchema);
//creating a schema for the visualizations
var vizSchema= mongoose.Schema({
vizName: String,
picture: { data: Buffer, contentType: String },
URL: String
},{
//_id: false,
versionKey : false
});
var VizModel = mongoose.model('VizModel', vizSchema);
db.once('open', function() {
console.log("connected to database");
// empty the collection
VizModel.remove(function (err) {
if (err) throw err;
console.error('removed old docs from VizModel');
// store an img in binary in mongo
var a = new VizModel;
a.picture.data = fs.readFileSync(imgPath1);
a.picture.contentType = 'image/png';
a.vizName="Wikipedia_Map";
a.URL="file:///C:/Users/Dani/Documents/GitHub/wikipediaMap/index.html";
a.save(function (err, a) {
if (err) throw err;
console.error('saved img to mongo');
express.get('/Wikipedia_Map', function (req, res, next) {
VizModel.findOne({vizName: "Wikipedia_Map"}, function (err, doc) {
if (err) return next(err);
res.contentType(doc.picture.contentType);
res.send(doc.picture.data);
});
});
});
var b = new VizModel;
b.picture.data = fs.readFileSync(imgPath2);
b.picture.contentType = 'image/png';
b.vizName="Twitter_Cascades";
b.URL="file:///C:/Users/Dani/Documents/GitHub/twitterCascades/index.html";
b.save(function (err, b) {
if (err) throw err;
console.error('saved img to mongo');
express.get('/Twitter_Cascades', function (req, res, next) {
VizModel.findOne({vizName: "Twitter_Cascades"}, function (err, doc) {
if (err) return next(err);
res.contentType(doc.picture.contentType);
res.send(doc.picture.data);
});
});
});
var c = new VizModel;
c.picture.data = fs.readFileSync(imgPath3);
c.picture.contentType = 'image/png';
c.vizName="Deleted_Tweets";
c.URL="file:///C:/Users/Dani/Documents/GitHub/deletedTweets/index.html";
c.save(function (err, c) {
if (err) throw err;
console.error('saved img to mongo');
express.get('/Deleted_Tweets', function (req, res, next) {
VizModel.findOne({vizName: "Deleted_Tweets"}, function (err, doc) {
if (err) return next(err);
res.contentType(doc.picture.contentType);
res.send(doc.picture.data);
});
});
});
var d = new VizModel;
d.picture.data = fs.readFileSync(imgPath0);
d.picture.contentType = 'image/png';
d.vizName="Filter";
d.URL="file:///C:/Users/Dani/Documents/GitHub/ms-filter/index.html";
d.save(function (err, d) {
if (err) throw err;
console.error('saved img to mongo');
express.get('/Filter', function (req, res, next) {
VizModel.findOne({vizName: "Filter"}, function (err, doc) {
if (err) return next(err);
res.contentType(doc.picture.contentType);
res.send(doc.picture.data);
});
});
});
});
});
function updateRoomID(socket) {
Room.findOne().sort({
$natural : -1
}).exec(function(err, result) {
if (err)
return console.error(err);
if (result == null) {
var id = 1;
try {
socket.emit("returnedRoomID", id);
} catch (e) {
console.log("not emitting -returnedRoomID- in if");
}
} else {
try {
var newid = result.roomID;
newid++;
socket.emit("returnedRoomID", newid);
} catch (e) {
console.log("not emitting -returnedRoomID-");
}
}
});
}
function getActiveRooms(socket){
Room.find().sort({$natural: -1}).exec(function(err,response){
if(err) return console.error(err);
try{
socket.emit("activeRooms", response);
}catch(e){
console.log("not emitting activeRooms");
}
});
}
function getRoomDetails(data){
Room.findOne({ roomID: data.id }, function(err, result){
if(err) return console.error(err);
try{
data.socket.emit("roomDetails", result);
}catch(e){
console.log("not emitting roomDetails event");
}
});
}
function getAttachedVizs(data){
Room.findOne({roomID:data.roomID}, function(err,docs){
var vizs=docs.attached_vizs;
VizModel.find({
'vizName': { $in: vizs}
}, function(err, docs){
if(err) console.error(err);
data.socket.emit('vizsURLS', {"vizDocs": docs, "roomID":data.roomID});
console.log(docs);
});
});
// for(int i=0; i<data.attached_vizs.length; i++){
// VizModel.findOne({vizName : data.attached_vizs[i]}, "URL", "vizName", function(err, response){
// if(err) return console.error(err);
// response.URL= response.URL+ "?room=" + data.roomID + "&vizName=" + response.vizName;
// vizs[i]=response;
// console.log(i+ " " +vizs[i]);
// });
//
//
// }
//
// if(vizs.length==data.attached_vizs.length){
// console.log("Array of vizs: ");
// console.log(vizs.length);
// }else{
// console.log("stupid thing");
// }
}
io.on('connection', function(socket) {
socket.on("getRoomDetails", function(data){
console.log("getRoomDetails event triggered");
getRoomDetails({"socket":socket, "id": data});
})
socket.on("updateRoom", function(data) {
console.log("updateRoom event triggered");
updateRoomID(socket);
});
socket.on("newRoom", function(data) {
console.log("newRoom event triggered");
var doc = new Room({
roomID : data.roomID,
roomName: data.roomName,
timeCreated : data.currentDate,
owner : "",
attached_vizs : data.attached_vizs,
active : data.active,
description : data.roomDesc,
stats : {}
});
doc.save(function(err, doc) {
if (err)
return console.error(err);
});
//getAttachedVizs(data);
console.log("NewRoom added to db");
socket.emit("roomCreated", "");
console.log(rooms);
});
socket.on('getActiveRooms', function(data){
console.log("getActiveRooms triggered");
getActiveRooms(socket);
});
socket.on('getURLS', function(data){
getAttachedVizs({"socket": socket, "roomID": data});
});
socket.on('newViz', function(data) {
var newViz = {};
newViz.vizName = data.vizName;
newViz.currentDate = data.currentDate;
console.log("");
console.log("NewViz created");
// if room exists
if (ds[data.room] != undefined) {
// push newViz in there
ds[data.room].vizs.push(newViz);
console.log(data.room + " already exists and " + newViz.vizName
+ " is in here");
// if room doesn't exist
} else {
ds[data.room] = {};
// add this new room the array of rooms
rooms.push(data.room);
ds[data.room].vizs = [];
ds[data.room].vizs.push(newViz);
// add an empty filter to the newly created room
ds[data.room].filter = {
// set the filter to this new room to false
"filter" : false,
"keyword_filter" : "",
"language_filter" : ""
};
// array for filters applied to this room
ds[data.room].filters_made = [];
console.log(data.room + " was just created and " + newViz.vizName
+ " was added to this room now");
// socket.emit("addNewRoom", data.room);
// socket.emit("filter", filter); // emit the current state to
// this client
}
// finally send newViz to the specified room
socket.join(data.room);
// socket.broadcast.to(data.room).emit('newVizJoined',
// newViz.vizName);
// show the filters in that room
socket.emit('existing_filters', ds[data.room].filters_made);
io.sockets.to(data.room).emit("set_filter_keyword",
ds[data.room].filter.keyword_filter);
console.log("set_filter keyword emitted");
io.sockets.to(data.room).emit("set_filter_lang",
ds[data.room].filter.language_filter);
console.log("set_filter lang emitted");
// emit this to the filter so that the filter checks the room and
// emits the right filter to the viz
// io.sockets.to(data.room).emit('checkRoom', {"vizName":
// newViz.vizName, "room": data.room});
console.log("The vizs in this room are: " + "\n" + ds[data.room].vizs);
console.log("Current Date HEREEEE:" + newViz.currentDate);
});
// my version of 'filter'
// should receive the filter and also the room that the filter applies
// to
socket.on("filter", function(data) {
console.log("Filter updated:", data.newFilter);
// if room exists update filter, combine it and send to clients in
// the
// specified room
if (ds[data.room] != undefined) {
_.extend(ds[data.room].filter, data.newFilter);
var tempFilter = ds[data.room].filter;
io.sockets.to(data.room).emit("filter", tempFilter.filter);
io.sockets.to(data.room).emit("set_filter_keyword",
tempFilter.keyword_filter);
io.sockets.to(data.room).emit("set_filter_lang",
tempFilter.language_filter);
} else {
console.log("Room doesn't exist");
}
});
socket.on('get_filter_list', function(room) {
// update with the last few items of the filter_list in that room
try {
var last_filters = ds[room].filters_made;
sendLastFilterItems({
"room" : room,
"last_filters" : last_filters.slice((last_filters.length - 3),
(last_filters.length - 1))
});
console.log("Filter list: " + "\n" + ds[room].filters_made);
} catch (e) {
// Might be an empty list...
}
});
// should also receive the room along with the newFilter
socket.on('filter_keyword', function(data) {
console.log("Filter_keyword updated:", data.newFilter);
if (ds[data.room] != undefined) {
var tempFilter = ds[data.room].filter;
tempFilter.filter = true;
tempFilter.keyword_filter = data.newFilter;
// emit to the sockets in the room
io.sockets.to(data.room).emit("filter", tempFilter.filter);
io.sockets.to(data.room).emit("set_filter_keyword",
tempFilter.keyword_filter);
// add the new filter to the filters_made
addToFilterList(data.room, "keyword", tempFilter.keyword_filter);
} else {
console.log("Room doesn't exist");
}
});
// receive a filter update, combine it and sent it to the clients in the
// specified ROOM!!
socket.on('filter_lang', function(data) {
if (ds[data.room] != undefined) {
var tempFilter = ds[data.room].filter;
tempFilter.filter = true;
tempFilter.language_filter = data.newFilter;
io.sockets.to(data.room).emit("filter", tempFilter.filter);
io.sockets.to(data.room).emit("set_filter_lang",
tempFilter.language_filter);
addToFilterList(data.room, "language", tempFilter.language_filter);
console.log("Filter_language updated:", data.newFilter);
} else {
console.log("Room doesn't exist");
}
});
// new ms user...
// receive a filter update, combine it and send to ALL clients
socket.on('active_user', function(newFilter) {
// console.log("filter updated:", newFilter);
// console.log("emitting filter:", filter);
++temp_user_cnt;
});
});
function emit_processed_message_count() {
if (processed_msg_cnt > 3000000) {
processed_msg_cnt = 0;
}
try {
io.emit("processed_msg_cnt", processed_msg_cnt);
} catch (e) {
console.log("failing here" + e)
}
}
// reset filters every 60 seconds - just for sanity...
// var processed_msgcnt_interval =
// setInterval(function(){emit_processed_message_count()}, 2000);
// send a list of initial items
function sendLastFilterItems(data) {
io.sockets.to(data.room).emit("existing_filters", data.last_filters);
}
// add to the current list of filters....IN THAT ROOM!!
// modified this function to also send the room as one of the parameters
function addToFilterList(room, type, filter_string) {
var date = new Date();
var data = {
"type" : type,
"filter" : filter_string,
"timestamp" : date
}
try {
ds[room].filters_made.push(data);
} catch (e) {
console.log("Failing here, room might not exist");
}
// change this emit to know what room we're talking about
io.sockets.to(room).emit("new_filter_item", data);
}
// reset all filters
function resetKeywords(room) {
keyword_filter = "";
language_filter = "";
// let the clients in that room know
io.sockets.to(room).emit("set_filter_keyword", keyword_filter);
io.sockets.to(room).emit("set_filter_lang", language_filter);
}
// reset filters every 60 seconds - just for sanity...
var resetKeywords_interval = setInterval(function(room) {
resetKeywords(room)
}, 1200000);
// Update the master count with the temp count
function updateUserCount() {
active_users = temp_user_cnt;
}
// want to send a heartbeat to all users to see how many are still connected!
function checkForUsers() {
// send a heartbeat
temp_user_cnt = 0;
io.emit("user_heartbeat", "blabla");
}
// want to send a heartbeat to all users to see how many are still connected!
function emitUserCount() {
// send a heartbeat
io.emit("active_user_count", active_users);
}
// These Control the User Count Details
var checkForUsers_interval = setInterval(function() {
checkForUsers()
}, 1000);
var updateUserCount_interval = setInterval(function() {
updateUserCount()
}, 2000);
var emit_userCount = setInterval(function() {
emitUserCount()
}, 1000);
// check filters for a particular room
function checkFilters(msg, room) {
var match_keyword = true;
var match_lang = true;
var tempFilter = ds[room].filter;
// is the filter enabled?
if (tempFilter.filter) {
// check for keyword filter
if (msg.content.toString().indexOf(tempFilter.keyword_filter) > -1) {
match_keyword = true;
} else {
match_keyword = false;
}
if (tempFilter.language_filter.length > 0) {
// var data = JSON.parse(msg.content.toString());
try {
if (msg.content.toString().indexOf(
'"' + tempFilter.language_filter + '"') > -1) {
match_lang = true;
} else {
match_lang = false;
}
} catch (e) {
console.log(e)
match_lang = false;
}
}
if (match_lang && match_keyword) {
return true;
} else {
return false;
}
} else {
return true;
}
}
// here we worry about the message sending
// We perform raw filtering here!
var emitMsg = function(outName, msg) {
try {
// ++processed_msg_cnt;
// loop through all the rooms in the ds and apply the right filters to
// each room
for (var room = 0; room < rooms.length; room++) {
if (checkFilters(msg, rooms[room])) {
var data = JSON.parse(msg.content.toString());
// emit data to that room?
io.to(rooms[room]).emit(outName, data);
// console.log(outName);
// make the revisions images feed
if (outName == "wikipedia_revisions") {
// console.log(ring());
var page_url = data.wikipedia_page_url;
if (page_url) {
wpimg(page_url).then(function(image) {
if (image && image != "") {
// emit to the entire room?
io.emit('wikipedia_images', {
"image_url" : image,
"data" : data
});
}
}, function(e) {
// error querying etc
});
}
}
// end of filter
}
}
// do a raw match on the message
} catch (e) {
//
}
}
var connectQueue = function(queueName, outName) {
return amqp.connect("amqp://admin:Sociam2015@sotonwo.cloudapp.net:5672")
.then(
function(conn) {
process.once('SIGINT', function() {
conn.close();
});
return conn.createChannel().then(
function(ch) {
var ok = ch.assertExchange(queueName,
'fanout', {
durable : false
});
ok = ok.then(function() {
return ch.assertQueue('', {
exclusive : true
});
});
ok = ok.then(function(qok) {
return ch.bindQueue(qok.queue,
queueName, '').then(function() {
return qok.queue;
});
});
ok = ok.then(function(queue) {
// function(msg,room)
return ch.consume(queue, function(msg) {
emitMsg(outName, msg);
}, {
noAck : true
});
});
return ok;
});
});
};
var connectQueueTwo = function(queueName, outName) {
return amqp.connect("amqp://wsi-h1.soton.ac.uk").then(function(conn) {
process.once('SIGINT', function() {
conn.close();
});
return conn.createChannel().then(function(ch) {
var ok = ch.assertExchange(queueName, 'fanout', {
durable : false
});
ok = ok.then(function() {
return ch.assertQueue('', {
exclusive : true
});
});
ok = ok.then(function(qok) {
return ch.bindQueue(qok.queue, queueName, '').then(function() {
return qok.queue;
});
});
ok = ok.then(function(queue) {
// function(msg, room)
return ch.consume(queue, function(msg) {
emitMsg(outName, msg);
}, {
noAck : true
});
});
return ok;
});
});
};
// var connect = connectQueue("wikipedia_hose", "wikipedia_revisions");
// connect = connect.then(function() { return connectQueue("twitter_hose",
// "tweets"); }, showErr);
// connect = connect.then(function() { return connectQueue("trends_hose",
// "trends"); }, showErr);
// for the larger spinn3r connection
var connect = connectQueueTwo("twitter_double", "spinn3r");
// connect = connect.then(function() { return connectQueueTwo("twitter_double",
// "spinn3r"); }, showErr);
// Wiki on the cluster
connect = connect.then(function() {
return connectQueueTwo("wikipedia_hose", "wikipedia_revisions");
}, showErr);
connect = connect.then(function() {
return connectQueueTwo("twitter_delete_hose", "twitter_delete");
}, showErr);
connect = connect.then(
function() {
return connectQueueTwo("twitter_delete_pulse_hose",
"twitter_delete_pulse");
}, showErr);
connect = connect.then(function() {
return connectQueueTwo("twitter_double", "twitter");
}, showErr);
// connect = connect.then(function() { return connectQueueTwo("news_hose",
// "news"); }, showErr);
connect = connect.then(function() {
return connectQueueTwo("zooniverse_classifications",
"zooniverse_classifications");
}, showErr);
connect = connect.then(function() {
return connectQueueTwo("zooniverse_talk", "zooniverse_talk");
}, showErr);
connect = connect.then(function() {
return connectQueueTwo("twitter_moocs", "twitter_moocs");
}, showErr);
// connect = connect.then(function() { return connectQueueTwo("twitter_moocs",
// "spinn3r"); }, showErr);
connect = connect.then(function() {
return connectQueueTwo("twitter_uk_southampton", "spinn3r");
}, showErr);
connect = connect.then(function() {
return connectQueueTwo("twitter_uk_southampton", "twitter_uk_southampton");
}, showErr);
// Finally, are we ready?
connect = connect.then(function() {
console.log("Ready at:" + startup_date);
}, showErr);