-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtmvis.js
3007 lines (2596 loc) · 123 KB
/
tmvis.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
'use strict'
/* ********************************
* AlSummarization
* An implementation for Ahmed AlSum's ECIR 2014 paper:
* "Thumbnail Summarization Techniques for Web Archives"
* Mat Kelly <[email protected]>
******************************************
* AlSummarization_OPT_CLI_JSON
* using the existing code and tweeking it to the code that returns the JSON Alone,
* And some code to be added to optimize the process of selecting which memento to
* be considered for simhash generation.
* OPT in the file name stands for optimization, Where id_ is appended at the end to return only the original content
* Run this with:
* > node AlSummarization_OPT_CLI_JSON.js urir
*
* Updated
* > node AlSummarization_OPT_CLI_JSON.js urir [--debug] [--hdt 4] [--ssd 0] [--ia || --ait || -mg] [--oes] [--ci 1068] [--os || --s&h]
* ex: node AlSummarization_OPT_CLI_JSON.js http://4genderjustice.org/ --oes --debug --ci 1068
* debug -> Run in debug mode
* hdt -> Hamming Distance Threshold
* ssd -> Screenshot delay
* ia -> Internet Archive
* ait -> Archive IT
* mg -> Memegator
* oes -> Override Existing Simhashes
* debug -> to get the debugging comments on the scree
* ci -> Collection Identifier, incase of ait
* os -> Only Simhash
* s&h -> Both Simhash and Hamming Distance
* Maheedhar Gunnam <[email protected]>
*/
var http = require('follow-redirects/http');
var express = require('express');
var url = require('url');
//var connect = require('connect');
//var serveStatic = require('serve-static');
// var Step = require('step');
var async = require('async');
// var Futures = require('futures');
var Promise = require('es6-promise').Promise;
var Async = require('async');
var simhash = require('simhash')('md5');
//var moment = require('moment');
//var ProgressBar = require('progress');
//var phantom = require('node-phantom');
var phantom = null;
var fs = require('fs');
var mdr = require('mkdir-recursive');
var path = require('path');
var validator = require('validator');
//var underscore = require('underscore');
//var webshot = require('webshot'); // PhantomJS wrapper
var webshot = null;
var argv = require('minimist')(process.argv.slice(2));
var mementoFramework = require('./lib/mementoFramework.js');
var Memento = mementoFramework.Memento;
var TimeMap = mementoFramework.TimeMap;
var SimhashCacheFile = require('./lib/simhashCache.js').SimhashCacheFile;
var colors = require('colors');
var im = require('imagemagick');
var rimraf = require('rimraf');
const puppeteer = require('puppeteer');
var HashMap = require('hashmap');
var cookieParser = require("cookie-parser");
var normalizeUrl = require("normalize-url");
var zlib = require('zlib');
var app = express();
var morgan = require('morgan');
var host = argv.host ? argv.host : 'localhost'; // Format: scheme://hostname
var port = argv.port ? argv.port : '3000';
var proxy = argv.proxy ? argv.proxy.replace(/\/+$/, '') : ('http://' + host + (port == '80' ? '' : ':' + port));
var localAssetServer = proxy + '/static/';
var isResponseEnded = false;
var isDebugMode = argv.debug? argv.debug: false;
var SCREENSHOT_DELTA = argv.ssd? argv.ssd: 2;
var isToOverrideCachedSimHash = argv.oes? argv.oes: false;
var isToComputeBoth = argv.os? false: true; // By default computes both simhash and hamming distance
var screenshotsLocation = "assets/screenshots/";
var streamingRes = null;
var streamedHashMapObj = new HashMap();
var responseDup = null;
var Stack = require('stackjs');
var mementosFromMultipleURIs = [];
var archivedMementos = [];
var maxMementos = argv.maxMementos? argv.maxMementos: 1000;
//var fullTimemap = new TimeMap();
//return
/* *******************************
TODO: reorder functions (main first) to be more maintainable 20141205
****************************** */
/**
* Start the application by initializing server instances
*/
function main () {
ConsoleLogIfRequired(('*******************************\r\n' +
'THUMBNAIL SUMMARIZATION SERVICE\r\n' +
'*******************************').blue);
ConsoleLogIfRequired("--By Mahee - for understanding");
// setting up the folder required
if (!fs.existsSync(__dirname+"/assets/screenshots")) {
//fs.mkdirSync(__dirname+"/assets/screenshots");
mdr.mkdirSync(__dirname+"/assets/screenshots");
}
if (!fs.existsSync(__dirname+"/cache")) {
fs.mkdirSync(__dirname+"/cache");
}
if (!fs.existsSync(__dirname+"/logs")) {
fs.mkdirSync(__dirname+"/logs");
}
//startLocalAssetServer() //- Now everything is made to be served from the same port.
var endpoint = new PublicEndpoint();
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'logs' ,'access.log'), {flags: 'a'});
var exceptionLogStream = fs.createWriteStream(path.join(__dirname, 'logs' ,'exception.log'), {flags: 'a'});
app.use(cookieParser());
// set a cookie
app.use(function (request, response, next) {
if(request._parsedUrl.pathname.indexOf("alsummarizedview") > 0 ) {
response.cookie('clientId',Date.now().toString());
}
next();
});
app.enable('trust proxy');
// all the common requests are logged via here
app.use(morgan('common',{
skip: function (req, res) {
if(req._parsedUrl.pathname.indexOf("notifications") > 0) {
return true;
}
return false;
},
stream: accessLogStream
}));
// to log all the exceptions in to exception log file
app.use(morgan('common',{
skip: function (req, res) { return res.statusCode < 400 },
stream: exceptionLogStream
}));
app.use(express.static(__dirname + '/public')); //This route is just for testing
app.use('/static', express.static(path.join(__dirname, 'assets/screenshots')));
//app.get(['/','/index.html','/alsummarizedview/:primesource/:ci/:hdt/:role/*'], (request, response) => {
app.get(['/','/index.html','/alsummarizedview/:primesource/:ci/:hdt/histogram/*','/index.html','/alsummarizedview/:primesource/:ci/:hdt/stats/*','/alsummarizedview/:primesource/:ci/:hdt/summary/*' ], (request, response) => {
response.sendFile(__dirname + '/public/index.html');
});
//This is just a hello test route
app.get('/hello', (request, response) => {
var headers = {}
// IE8 does not allow domains to be specified, just the *
// headers['Access-Control-Allow-Origin'] = req.headers.origin
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET';
headers['Access-Control-Allow-Credentials'] = false;
headers['Access-Control-Max-Age'] = '86400'; // 24 hours
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Accept-Datetime';
headers['Content-Type'] = 'text/html'; // text/html
var query = url.parse(request.url, true).query;
console.log(JSON.stringify(query));
response.writeHead(200, headers);
response.write('Hello from what ever!');
response.end();
});
//For individual memento refresh
app.get('/refreshscreenshot', (request, response) => {
refreshMemento(request, response);
});
//that a work around to clear the streaming realted cache
app.get('/clearstreamhash', (request, response) => {
var headers = {}
// IE8 does not allow domains to be specified, just the *
// headers['Access-Control-Allow-Origin'] = req.headers.origin
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET';
headers['Access-Control-Allow-Credentials'] = false;
headers['Access-Control-Max-Age'] = '86400' ; // 24 hours
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Accept-Datetime';
headers['Content-Type'] = 'text/html' ;// text/html
var query = url.parse(request.url, true).query;
console.log(JSON.stringify(query));
streamedHashMapObj.clear();
response.writeHead(200, headers);
response.write('cleared the streaming hash');
response.end();
});
//This route is just for testing, testing the SSE
app.get('/notifications/:curUniqueUserSessionID', (request, response) => {
sendSSE(request, response);
})
// this is the actually place that hit the main server logic
//app.get('/alsummarizedtimemap/:primesource/:ci/:urir', endpoint.respondToClient)
app.get('/alsummarizedtimemap/:primesource/:ci/:hdt/:role/:from/:to/*', endpoint.respondToClient);
app.listen(port, '0.0.0.0', (err) => {
if (err) {
return console.log('something bad happened', err);
}
console.log(`server is listening on ${port}`);
});
}
/**
* Handles request to retake the given screenshot
*
* @param request - http request that consists of parameters, query string, http headers and so on
* @param response - http response sent after a request is acquired and evaluated
*/
function refreshMemento(request, response) {
var headers = {}
// IE8 does not allow domains to be specified, just the *
// headers['Access-Control-Allow-Origin'] = req.headers.origin
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET';
headers['Access-Control-Allow-Credentials'] = false;
headers['Access-Control-Max-Age'] = '86400'; // 24 hours
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Accept-Datetime';
headers['Content-Type'] = 'text/html'; // text/html
var curCookieClientId = request.headers["x-my-curuniqueusersessionid"];
var mementoURI = request.query.link;
var file = request.query.img;
file = file.split("static/")[1];
var memento = {screenshotURI: file, uri: mementoURI};
console.log("File: "+file);
console.log("URI: "+mementoURI);
try{
fs.unlink(screenshotsLocation+file,function() {}); //deleting old screenshot
var tempTimemap = new TimeMap();
async.series([
function(callback) {
tempTimemap.createScreenshotForMementoWithPuppeteer(curCookieClientId,memento,response,true,callback); // take new screenshot
},
function(callback) {
response.writeHead(200, headers);
response.end();
callback();
}],
function(err) {
if(err) {
console.log("Error: "+err);
response.writeHead(405,headers);
response.end();
}
}
);
} catch(e) {
response.writeHead(405,headers);
}
}
// SSE Related.
function sendSSE(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
if( !streamedHashMapObj.has(req.params.curUniqueUserSessionID)) {
streamedHashMapObj.set(req.params.curUniqueUserSessionID,res);
}
}
/**
* Constructs a server-sent event
*
* @param request The request object from the client representing query information
* @param response Currently active HTTP response to the client used to return information to the client based on the request
*/
function constructSSE(data,clientIdInCookie) {
var id = Date.now();
var streamObj = {};
var curResponseObj= null;
streamObj.data= data;
if(clientIdInCookie != undefined && clientIdInCookie != null) {
streamObj.usid = clientIdInCookie;
} else {
streamObj.usid = 100;
}
console.log("clientIdInCookie --->"+clientIdInCookie);
console.log("streamedHashMapObj keys --->"+streamedHashMapObj.keys().toString());
console.log("count --->"+ streamedHashMapObj.count());
curResponseObj=streamedHashMapObj.get(clientIdInCookie);
if(curResponseObj != null) {
console.log("From retrieved Response Obj -->"+curResponseObj);
curResponseObj.write('id: ' + id + '\n');
curResponseObj.write("data: " + JSON.stringify(streamObj) + '\n\n');
if(data === "readyToDisplay" || data === "statssent" ) {
streamedHashMapObj.delete(clientIdInCookie);
}
}
}
function doesBelongInCollection(yearsArry,memento) {
var dateTimeStr = memento["datetime"];
var curMemYear = new Date(dateTimeStr).getFullYear();
if(yearsArry.indexOf(curMemYear) != -1) {
return true;
}
return false;
}
/**
* Setup the public-facing attributes of the service
*/
function PublicEndpoint() {
var theEndPoint = this;
// Parameters supplied for means of access:
this.validSource = ['archiveit', 'internetarchive', 'arquivopt'];
this.isAValidSourceParameter = function (accessParameter) {
return theEndPoint.validSource.indexOf(accessParameter) > -1;
}
/**
* Handle an HTTP request and respond appropriately
* @param request The request object from the client representing query information
* @param response Currently active HTTP response to the client used to return information to the client based on the request
*/
this.respondToClient = function (request, response) {
ConsoleLogIfRequired("#################### Response header ##########");
ConsoleLogIfRequired(request.headers["x-my-curuniqueusersessionid"]);
ConsoleLogIfRequired("############################################");
responseDup = response;
ConsoleLogIfRequired("Cookies------------------>"+request.headers["x-my-curuniqueusersessionid"]);
constructSSE("streamingStarted",request.headers["x-my-curuniqueusersessionid"]);
constructSSE("percentagedone-3",request.headers["x-my-curuniqueusersessionid"]);
isResponseEnded = false; //resetting the responseEnded indicator
//response.clientId = Math.random() * 101 | 0 // Associate a simple random integer to the user for logging (this is not scalable with the implemented method)
response.clientId = request.headers["x-my-curuniqueusersessionid"];
var headers = {}
// IE8 does not allow domains to be specified, just the *
// headers['Access-Control-Allow-Origin'] = req.headers.origin
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET';
headers['Access-Control-Allow-Credentials'] = false;
headers['Access-Control-Max-Age'] = '86400'; // 24 hours
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Accept-Datetime';
if (request.method !== 'GET') {
console.log('Bad method ' + request.method + ' sent from client. Try HTTP GET');
response.writeHead(405, headers);
response.end();
return;
}
// var response ={}
var URIRFromCLI = "";
//var query = url.parse(request.url, true).query
console.log(request.params);
var query ={};
query['urir'] = request.params["0"] + (request._parsedUrl.search != null ? request._parsedUrl.search : '');
console.log(query['urir']);
query['ci']= request.params.ci;
query['primesource']= request.params.primesource;
query['hdt']= request.params.hdt;
// for the intermediate step of involving user to decide the value of k
query['role']= request.params.role;
console.log(query['role']);
/*
if(query['role'].length > 9) {// if date range was passed with role
query['from'] = query['role'].substring(7,17); // extract from date
query['to'] = query['role'].substring(17,27); // extract to date
query['role'] = query['role'].substring(0,7); // set role back to summary
} else {
query['from'] = 0 // extract from date
query['to'] = 0
}*/
if(request.params.from != '0') {
query['from'] = request.params.from;
query['to'] = request.params.to;
} else {
query['from'] = 0;
query['to'] = 0;
}
query['ssd']=request.params.ssd;
ConsoleLogIfRequired("--- ByMahee: Query URL from client = "+ JSON.stringify(query));
/******************************
IMAGE PARAMETER - allows binary image data to be returned from service
**************************** */
if (query.img) {
// Return image data here
var fileExtension = query.img.substr('-3'); // Is this correct to use a string and not an int!?
ConsoleLogIfRequired('fetching ' + query.img + ' content');
var img = fs.readFileSync(__dirname + '/' + query.img);
ConsoleLogIfRequired("200, {'Content-Type': 'image/'" + fileExtension +'}');
return;
}
/******************************
URIR PARAMETER - required if not img, supplies basis for archive query
**************************** */
function isARESTStyleURI (uri) {
return (uri.substr(0, 5) === '/http');
}
if (!query['urir'] && // a urir was not passed via the query string...
request._parsedUrl && !isARESTStyleURI(request._parsedUrl.pathname.substr(0, 5))) { // ...or the REST-style specification
response.writeHead(400, headers);
response.write('No urir Sent with the request');
response.end();
return;
} else if (request._parsedUrl && !query['urir']) {
// Populate query['urir'] with REST-style URI and proceed like nothing happened
query['urir'] = request._parsedUrl.pathname.substr(1);
} else if (query['urir']) { // urir is specied as a query parameter
console.log('urir valid, using query parameter.');
}
// Override the default access parameter if the user has supplied a value
// via query parameters
if (query.primesource) {
query.primesource = query.primesource.toLowerCase();
}
if (isNaN(query.hdt)) {
query.hdt = 4 ;// setting to default hamming distance threshold
} else {
query.hdt = parseInt(query.hdt);
}
if(query.role === "stats") {
} else if(query.role === "summary") {
} else if(query.role === "histogram") {
} else {
query.role = "histogram";
}
if (isNaN(query.ssd)) {
SCREENSHOT_DELTA = 2; // setting to default screenshot delay time
} else {
SCREENSHOT_DELTA = parseInt(query.ssd);
}
if (!theEndPoint.isAValidSourceParameter(query.primesource)) { // A bad access parameter was passed in
console.log('Bad source query parameter: ' + query.primesource);
response.writeHead(501, headers);
response.write('The source parameter was incorrect. Try one of ' + theEndPoint.validSource.join(',') + ' or omit it entirely from the query string\r\n');
response.end();
return;
}
headers['X-Means-Of-Source'] = query.primesource;
var strategy = "alSummarization";
headers['X-Summarization-Strategy'] = strategy;
var URIs = query['urir'].split(",");
if(URIs.length == 0)
URIs = [query.urir];
for (var i = 0; i < URIs.length; i++) {
if (!URIs[i].match(/^[a-zA-Z]+:\/\//)) {
URIs[i] = 'http://' + URIs[i];
}// Prepend scheme if missing
}
headers['Content-Type'] = 'application/json';//'text/html'
response.writeHead(200, headers);
ConsoleLogIfRequired('New client request urir: ' + query['urir'] + '\r\n> Primesource: ' + query.primesource + '\r\n> Strategy: ' + strategy);
for (var i = 0; i < URIs.length; i++) {
if (!validator.isURL(URIs[i])) { // Return "invalid URL"
console.log(query['urir']);
consoleLogJSONError('Invalid URI');
//response.writeHead(200, headers);
response.write('Invalid urir \r\n');
response.end();
return;
}
}
function consoleLogJSONError (str) {
ConsoleLogIfRequired('{"Error": "' + str + '"}');
}
if ( isNaN(query.ci)) {
query.ci = 'all';
} else {
query.ci = parseInt(query.ci);
}
// ByMahee -- setting the incoming data from request into response Object
response.thumbnails = []; // Carry the original query parameters over to the eventual response
response.thumbnails['primesource'] = query.primesource;
response.thumbnails['strategy'] = strategy;
response.thumbnails['collectionidentifier'] = query.ci;
response.thumbnails['hammingdistancethreshold'] = query.hdt;
response.thumbnails['role'] = query.role;
response.thumbnails['urir'] = query.urir;
if(query['from'] != 0) {// if a from date was given
response.thumbnails['from'] = query['from'];
response.thumbnails['to'] = query['to'];
} else {
response.thumbnails['from'] = 0;
response.thumbnails['to'] = 0;
}
/*TODO: include consideration for strategy parameter supplied here
If we consider the strategy, we can simply use the TimeMap instead of the cache file
Either way, the 'response' should be passed to the function representing the chosen strategy
so the function still can return HTML to the client
*/
var t = new TimeMap();
t.originalURI = query.urir;
t.primesource = query.primesource;
t.collectionidentifier = query.ci;
t.hammingdistancethreshold = query.hdt;
t.role = query.role;
//for(var i in URIs)
//URIs[i] = urlCanonicalize(URIs[i]);
// If more than 1 URI was passed at once, check if each individual URI has been cached.
// If not, cache it. Then merge the timemaps of each URI for the user.
if(URIs.length > 1) {
mementosFromMultipleURIs = [];
processMultipleURIs(t, query, response, request.headers["x-my-curuniqueusersessionid"]);
} else {
// TODO: optimize this out of the conditional so the functions needed for each strategy are self-contained (and possibly OOP-ified)
if (strategy === 'alSummarization') {
var originalURI = urlCanonicalize(query['urir']);
var histogramFile = new SimhashCacheFile(query.primesource+"_"+query.ci+"_"+originalURI,isDebugMode);
histogramFile.path = histogramFile.path.replace("simhashes","histogram");
histogramFile.path += ".json";
archivedMementos = JSON.parse(histogramFile.readFileContentsSync());
var cacheFile = new SimhashCacheFile( query.primesource+"_"+query.ci+"_"+originalURI,isDebugMode);
cacheFile.path += '.json';
ConsoleLogIfRequired('Checking if a cache file exists for ' + query['urir'] + '...');
constructSSE('Checking if a cache file exists for ' + query['urir'] + '...',request.headers["x-my-curuniqueusersessionid"]);
constructSSE("percentagedone-10",request.headers["x-my-curuniqueusersessionid"]);
// ConsoleLogIfRequired('cacheFile: '+JSON.stringify(cacheFile))
cacheFile.readFileContents(
function success (data) {
// A cache file has been previously generated using the alSummarization strategy
// ByMahee -- ToDo: We can even add a prompt from user asking whether he would want to recompute hashes here
ConsoleLogIfRequired("**ByMahee** -- readFileContents : Inside Success ReadFile Content, processWithFileContents is called next ");
if(isToOverrideCachedSimHash) {
ConsoleLogIfRequired("Responded to compute latest simhahes, Proceeding...");
getTimemapGodFunctionForAlSummarization(query['urir'], response,request.headers["x-my-curuniqueusersessionid"]);
} else if(t.role == "histogram") {
ConsoleLogIfRequired("Responded to grab latest set of mementos");
getTimemapGodFunctionForAlSummarization(query['urir'], response,request.headers["x-my-curuniqueusersessionid"]);
} else {
ConsoleLogIfRequired("Responded to continue with the exisitng cached simhashes file. Proceeding..");
constructSSE('cached simhashes exist, proceeding with cache...',request.headers["x-my-curuniqueusersessionid"]);
constructSSE("percentagedone-15",request.headers["x-my-curuniqueusersessionid"]);
processWithFileContents(query['urir'], data, response,request.headers["x-my-curuniqueusersessionid"]);
}
},
function failed () {
//ByMahee -- calling the core function responsible for AlSummarization, if the cached file doesn't exist
ConsoleLogIfRequired("**ByMahee** -- readFileContents : Inside Failed ReadFile Content (meaning file doesn't exist), getTimemapGodFunctionForAlSummarization is called next ");
constructSSE("cached simhashes doesn't exist, proceeding to compute the simhashes...",request.headers["x-my-curuniqueusersessionid"]);
getTimemapGodFunctionForAlSummarization(query['urir'], response,request.headers["x-my-curuniqueusersessionid"]);
}
);
}
}
}
}
/**
* Delete all derived data including caching and screenshot - namely for testing
* @param cb Callback to execute upon completion
*/
function cleanSystemData (cb) {
// Delete all files in ./screenshots/ and ./cache/
var dirs = ['assets/screenshots', 'assets/cache'];
dirs.forEach(function (e, i) {
rimraf(__dirname + '/' + e + '/*', function (err) {
if (err) {
throw err;
}
ConsoleLogIfRequired('Deleted contents of ./' + e + '/');
});
ConsoleLogIfRequired(e);
});
if (cb) {
cb();
}
}
/**
* When the user enters multiple URIs, each individual URI is checked to see if cached.
* After caching the appropriate URIs the timemaps are then combined and processed.
*
* @param t - The passed timemap object
*/
function processMultipleURIs(t, query, response, curCookieClientId) {
var uriList = query['urir'].split(',');
async.series([
function(callback) {
checkIfCachedForMultipleURIs(uriList, query, response, curCookieClientId, callback);
},
function(callback) {
t.mementos = t.mementos.concat(mementosFromMultipleURIs);
if(response.thumbnails['from'] != 0) {
t.filterMementosForDateRange(response, callback);
} else
callback('');
},
function(callback) {
if(t.mementos.length > maxMementos && t.role != "histogram") {
t.filterMementos(response, curCookieClientId, callback);
} else
callback('');
},
function (callback) {
if(t.role == "stats") {
t.calculateHammingDistancesWithOnlineFiltering(curCookieClientId,callback);
} else if(t.role == "histogram") {
callback('');
} else {
t.calculateHammingDistancesWithOnlineFilteringForSummary(curCookieClientId,callback);
}
constructSSE("percentagedone-5",curCookieClientId);
},
function (callback) {
if(t.role == "stats") {
t.supplyChosenMementosBasedOnHammingDistanceAScreenshotURI(callback);
} else if(t.role == "histogram") {
callback('');
} else {
t.supplyChosenMementosBasedOnHammingDistanceAScreenshotURIForSummary(callback);
}
constructSSE("percentagedone-15",curCookieClientId);
},
function (callback) {
ConsoleLogIfRequired('****************curCookieClientId from processWithFileContents ->'+curCookieClientId +' *********');
constructSSE("percentagedone-20",curCookieClientId);
if (t.role == "histogram") {
t.getDatesForHistogram(callback,response,curCookieClientId, null);
} else {
t.createScreenshotsForMementos(curCookieClientId,response,callback);
}
},
function (callback) {
constructSSE('Writing the data into cache file for future use...',curCookieClientId);
constructSSE("percentagedone-95",curCookieClientId);
if (t.role == "histogram") {
callback('');
} else {
t.writeThumbSumJSONOPToCache(response);
}
}],
function(err) {
if(err) {
console.log(err);
}
}
);
}
/**
* Checks if each of the given URIs have been cached.
* If a URI has not been cached, the timemap is fetched and cached.
* Else, the cache file is read.
*
* @param uriList - The list of user input URIs
* @param response handler to client's browser interface
*/
function checkIfCachedForMultipleURIs(uriList, query, response, curCookieClientId, callback) {
async.eachLimit(uriList, 1, function(uri, callback) {
var originalURI = urlCanonicalize(uri);
var cacheFile = new SimhashCacheFile(query.primesource+"_"+query.ci+"_"+originalURI,isDebugMode);
cacheFile.path += ".json";
if (!(fs.existsSync(cacheFile.path)) || query['role'] == "histogram") {
getTimemapForMultipleURIs(uri, query, response, curCookieClientId, callback);
} else {
var histogramFile = new SimhashCacheFile(query.primesource+"_"+query.ci+"_"+originalURI,isDebugMode);
histogramFile.path = histogramFile.path.replace("simhashes","histogram");
histogramFile.path += ".json";
archivedMementos = JSON.parse(histogramFile.readFileContentsSync());
var data = fs.readFileSync(cacheFile.path, 'utf-8');
var curTimeMap = createMementosFromJSONFile(data);
curTimeMap.originalURI = originalURI;
curTimeMap.primesource = query.primesource;
curTimeMap.collectionidentifier = query.ci;
curTimeMap.hammingdistancethreshold = query.hdt;
curTimeMap.role = query.role;
async.series([
function(callback) {
if(response.thumbnails['from'] != 0) {
curTimeMap.filterMementosForDateRange(response, callback);
} else
callback('');
},
function (callback) {
var histogramFile = new SimhashCacheFile(response.thumbnails["primesource"]+"_"+response.thumbnails["collectionidentifier"]+"_"+urlCanonicalize(uri),isDebugMode);
histogramFile.path = histogramFile.path.replace("simhashes","histogram");
histogramFile.path += ".json";
archivedMementos = JSON.parse(histogramFile.readFileContentsSync());
curTimeMap.matchMementosToArchive(originalURI, response, curCookieClientId, data, callback);
},
function (callback) {
curTimeMap.getDatesForHistogram(callback,response,curCookieClientId, true);
}
],
function(err){
if(err) {
console.log(err);
return;
}
mementosFromMultipleURIs = mementosFromMultipleURIs.concat(curTimeMap.mementos);
callback();
}
);
}},
function(err) {
if(err) {
console.log(err);
return;
}
if(callback) {
callback();
}
}
);
}
/**
* Caches the timemap for the provided URI and appends the mementos to mementosFromMultipleURIs.
* Else, the cache file is read.
*
* @param uri - The URI of the timemap to be cached
* @param response - Handler to client's browser interface
* @param update - If true, the cache file for the URI has less mementos than requested by the user
* and needs updated.
*/
function getTimemapForMultipleURIs (uri, query, response, curCookieClientId, callback) {
var t = new TimeMap();
var retStr = '';
var metadata = '';
ConsoleLogIfRequired('Starting many asynchronous operationsX...');
async.series([
function(callback) {
t.fetchTimemap(uri, response, curCookieClientId, callback);
},
function(callback) {
if(response.thumbnails['from'] != 0 && t.mementos.length != 0) {
t.filterMementosForDateRange(response, callback);
} else
callback('');
},
function (callback) {
if ((t.hammingdistancethreshold == '0' && t.role == "summary") || t.mementos.length == 0 || t.role == "histogram") {
callback('');
} else {
t.calculateSimhashes(curCookieClientId,response,callback);
}
},
function (callback) {
constructSSE("percentagedone-30",curCookieClientId);
if (t.role == "histogram" || (t.hammingdistancethreshold == '0' && t.role == "summary") || t.mementos.length == 0) {
callback('');
} else {
t.saveSimhashesToCache(callback);
}
},
function (callback) {
if(t.hammingdistancethreshold == '0' && t.role == "summary" && t.mementos.length != 0) {
t.supplyAllMementosAScreenshotURI(callback);
}else if(t.role == "histogram") {
t.getDatesForHistogram(callback,response,curCookieClientId,true);
} else if (t.mementos.length != 0) {
t.writeJSONToCache(callback);
} else {
callback('');
}
}],
function (err, result) {
if (err) {
ConsoleLogIfRequired('ERROR!');
ConsoleLogIfRequired(err);
} else {
ConsoleLogIfRequired('There were no errors executing the callback chain');
if(t.mementos.length != 0) {
mementosFromMultipleURIs = mementosFromMultipleURIs.concat(t.mementos);
}
callback();
}
}
);
}
/**
* Display thumbnail interface based on passed in JSON
* @param fileContents JSON string consistenting of an array of mementos
* @param response handler to client's browser interface
*/
function processWithFileContents (uri, fileContents, response, curCookieClientId) {
var histogramFile = new SimhashCacheFile(response.thumbnails["primesource"]+"_"+response.thumbnails["collectionidentifier"]+"_"+urlCanonicalize(uri),isDebugMode);
histogramFile.path = histogramFile.path.replace("simhashes","histogram");
histogramFile.path += ".json";
archivedMementos = JSON.parse(histogramFile.readFileContentsSync());
var t = createMementosFromJSONFile(fileContents);
t.curClientId = curCookieClientId;
t.originalURI = urlCanonicalize(response.thumbnails['urir']);
t.primesource = response.thumbnails['primesource'];
t.collectionidentifier = response.thumbnails['collectionidentifier'];
t.hammingdistancethreshold = response.thumbnails['hammingdistancethreshold'];
t.role = response.thumbnails['role'];
/* ByMahee -- unnessessary for the current need
t.printMementoInformation(response, null, false) */
if(t.mementos.simhash === 'undefined') {
getTimemapGodFunctionForAlSummarization(uri, response,curCookieClientId);
} else {
ConsoleLogIfRequired("Existing file contents are as follows:");
ConsoleLogIfRequired("**************************************************************************************************");
console.log(JSON.stringify(t));
if(isToComputeBoth) {
constructSSE('streamingStarted',curCookieClientId);
async.series([
function (callback) {
if(response.thumbnails['from'] != 0) {
t.filterMementosForDateRange(response, callback);
} else {
callback('');
}
},
function (callback) {
if(t.mementos.length > maxMementos && t.role != "histogram") {
t.filterMementos(response, curCookieClientId, callback)
} else
callback('');
},
function (callback) {
t.matchMementosToArchive(uri, response, curCookieClientId, fileContents, callback);
},
function (callback) {
if(t.role == "stats") {
t.calculateHammingDistancesWithOnlineFiltering(curCookieClientId,callback);
} else if(t.role == "histogram") {
callback('');
}else{
t.calculateHammingDistancesWithOnlineFilteringForSummary(curCookieClientId,callback);
}
constructSSE("percentagedone-5",curCookieClientId);
},
function (callback) {
if(t.role == "stats") {
t.supplyChosenMementosBasedOnHammingDistanceAScreenshotURI(callback);
} else if(t.role == "histogram") {
callback('');
} else {
t.supplyChosenMementosBasedOnHammingDistanceAScreenshotURIForSummary(callback);
}
constructSSE("percentagedone-15",curCookieClientId);
},
function (callback) {
ConsoleLogIfRequired('****************curCookieClientId from processWithFileContents ->'+curCookieClientId +' *********');
constructSSE("percentagedone-20",curCookieClientId);
if (t.role == "histogram") {
t.getDatesForHistogram(callback,response,curCookieClientId, false);
} else {
t.createScreenshotsForMementos(curCookieClientId,response,callback);
}
},
function (callback) {
constructSSE('Writing the data into cache file for future use...',curCookieClientId);
constructSSE("percentagedone-95",curCookieClientId);
if (t.role == "histogram") {
callback('');
} else {
t.writeThumbSumJSONOPToCache(response);
}
}],
function (err, result) {
if (err) {
console.log('ERROR!');
console.log(err);
} else {
constructSSE('Finshed writing into cache...',curCookieClientId);
constructSSE("percentagedone-100",curCookieClientId);
console.log('There were no errors executing the callback chain');
}
}
);
}
}
}
/**
* Convert a string from the JSON cache file to Memento objects
* @param fileContents JSON string consistenting of an array of mementos
*/
function createMementosFromJSONFile (fileContents) {
var t = new TimeMap();
t.mementos = JSON.parse(fileContents);
return t;
}
/**
* String representation of a timemap object
*/
TimeMap.prototype.toString = function () {
return '{' +
'"timemaps":[' + this.timemaps.join(',') + '],' +
'"timegates":[' + this.timegates.join(',') + '],' +
'"mementos":[' + this.mementos.join(',') + ']' +
'}';
}
/**
* Extend Memento object to be more command-line friendly without soiling core
*/
Memento.prototype.toString = function () {
return JSON.stringify(this);
}
// Add Thumbnail Summarization attributes to Memento Class without soiling core
Memento.prototype.simhash = null;
Memento.prototype.captureTimeDelta = -1;
Memento.prototype.hammingDistance = -1;
Memento.prototype.simhashIndicatorForHTTP302 = '00000000';
/**
* Fetch URI-M HTML contents and generate a Simhash
*
* @param theTimemap - the timemap object this memento belong to
*/
Memento.prototype.setSimhash = function (theTimeMap,curCookieClientId,response,callback) {