-
Notifications
You must be signed in to change notification settings - Fork 7
/
tmvisWithMergerAndMinMaxHD.js
1630 lines (1305 loc) · 58.1 KB
/
tmvisWithMergerAndMinMaxHD.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 <mkelly@cs.odu.edu>
******************************************
* 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] [--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
* 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 <mgunn001@odu.edu>
*/
var http = require('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 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 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')
//var faye = require('faye') // For status-based notifications to client
// Faye's will not allow a URI-* as the channel name, hash it for Faye
//var md5 = require('md5')
var zlib = require('zlib')
var app = express()
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 uriR = ''
var isDebugMode = argv.debug? argv.debug: false
//var HAMMING_DISTANCE_THRESHOLD = argv.hdt? argv.hdt: 4
var HAMMING_DISTANCE_Min_THRESHOLD = argv.minhdt? argv.minhdt: 1
var HAMMING_DISTANCE_Max_THRESHOLD = argv.maxhdt? argv.maxhdt: 4
var isToOverrideCachedSimHash = argv.oes? argv.oes: false
// by default the prime src is gonna be Archive-It
var primeSrc = argv.ait? 1: (argv.ia ? 2:(argv.mg?3:1))
var primeSource = "archiveit"
var isToComputeBoth = argv.os? false: true // By default computes both simhash and hamming distance
var collectionIdentifier = argv.ci? argv.ci: 'all'
var screenshotsLocation = "assets/screenshots/"
ConsoleLogIfRequired("Hamming distance thresholds set while running the server: min->"+HAMMING_DISTANCE_Min_THRESHOLD+" max-> "+HAMMING_DISTANCE_Max_THRESHOLD)
//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");
}
//startLocalAssetServer() //- Now everything is made to be served from the same port.
var endpoint = new PublicEndpoint()
//This route is just for testing
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'] = 'application/json' // 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()
})
// this is the actually place that hit the main server logic
//app.get('/alsummarizedtimemap/:primesource/:ci/:urir', endpoint.respondToClient)
app.get('/alsummarizedtimemap/:primesource/:ci/*', endpoint.respondToClient)
app.use('/static', express.static(path.join(__dirname, 'assets/screenshots')))
app.listen(port, '0.0.0.0', (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
}
/**
* Setup the public-facing attributes of the service
*/
function PublicEndpoint () {
var theEndPoint = this
// Parameters supplied for means of access:
this.validSource = ['archiveit', 'internetarchive'];
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) {
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)
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
var query ={};
query['urir'] = request.params["0"] + (request._parsedUrl.search != null ? request._parsedUrl.search : '');
query['ci']= request.params.ci;
query['primesource']= request.params.primesource;
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
console.log('No urir sent with request. ' + request.url + ' was sent. Try ' + proxy + '/archiveit/1068/http://matkelly.com')
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.')
}
// ByMahee --- Actually URI is being set here
uriR = query['urir']
ConsoleLogIfRequired("--ByMahee: uriR = "+uriR)
primeSource = theEndPoint.validSource[0] // Not specified? access=interface
// Override the default access parameter if the user has supplied a value
// via query parameters
if (query.primesource) {
primeSource = query.primesource.toLowerCase()
}
if (!theEndPoint.isAValidSourceParameter(primeSource)) { // A bad access parameter was passed in
console.log('Bad source query parameter: ' + 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'] = primeSource
var strategy = "alSummarization"
headers['X-Summarization-Strategy'] = strategy
if(primeSource == 'archiveit'){
primeSrc = 1
}else if(primeSource == 'internetarchive'){
primeSrc = 2
}else{
primeSrc = 3
}
if (!uriR.match(/^[a-zA-Z]+:\/\//)) {
uriR = 'http://' + uriR
}// Prepend scheme if missing
headers['Content-Type'] = 'application/json' //'text/html'
response.writeHead(200, headers)
// response.write('New client request urir: ' + query['urir'] + '\r\n> Primesource: ' + primeSource + '\r\n> Strategy: ' + strategy);
// response.end()
ConsoleLogIfRequired('New client request urir: ' + query['urir'] + '\r\n> Primesource: ' + primeSource + '\r\n> Strategy: ' + strategy)
if (!validator.isURL(uriR)) { // Return "invalid URL"
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)){
collectionIdentifier = 'all'
}else {
collectionIdentifier = 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'] = primeSource
response.thumbnails['strategy'] = strategy
response.thumbnails['collectionidentifier'] = collectionIdentifier
/*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']
// 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 cacheFile = new SimhashCacheFile( primeSource+"_"+collectionIdentifier+"_"+uriR,isDebugMode)
cacheFile.path += '.json'
ConsoleLogIfRequired('Checking if a cache file exists for ' + query['urir'] + '...')
// 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)
}else{
ConsoleLogIfRequired("Responded to continue with the exisitng cached simhashes file. Proceeding..");
processWithFileContents(data, response)
}
//ByMahee -- UnComment Following Line(UCF)
// processWithFileContents(data, response)
},
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 ")
//ByMahee -- UCF
getTimemapGodFunctionForAlSummarization(query['urir'], response)
}
)
}
}
}
/**
* 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()
}
}
/**
* 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 (fileContents, response) {
var t = createMementosFromJSONFile(fileContents)
t.originalURI = uriR
/* ByMahee -- unnessessary for the current need
t.printMementoInformation(response, null, false) */
ConsoleLogIfRequired("Existing file contents are as follows:")
ConsoleLogIfRequired("**************************************************************************************************");
console.log(JSON.stringify(t));
if(isToComputeBoth){
async.series([
function (callback) {t.calculateHammingDistancesWithOnlineFiltering(callback)},
function (callback) {t.supplyChosenMementosBasedOnHammingDistanceAScreenshotURI(callback)},
function (callback) {t.createScreenshotsForMementos(response,callback)},
function (callback) {t.writeThumbSumJSONOPToCache(response)}
],
function (err, result) {
if (err) {
console.log('ERROR!')
console.log(err)
} else {
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
}
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
*/
Memento.prototype.setSimhash = function (callback) {
// Retain the urir for reference in the promise (this context lost with async)
var thaturi = this.uri
var thatmemento = this
var buffer2 = ''
var memento = this // Potentially unused? The 'this' reference will be relative to the promise here
var mOptions = url.parse(thaturi)
ConsoleLogIfRequired('Starting a simhash: ' + mOptions.host + mOptions.path)
var req = http.request({
'host': mOptions.host,
'path': mOptions.path,
'port':80,
'headers': {'User-Agent': 'TimeMap Summarization instance - Contact (@WebSciDL)Twitter, (@maheedhargunnam)Twitter'}
}, function (res) {
// var hd = new memwatch.HeapDiff()
if (res.statusCode !== 200) { // setting the simhash to be '0000000' for all the mementos which has a status of non 200
thatmemento.simhash = Memento.prototype.simhashIndicatorForHTTP302
}
var outputBuffer;
// res.setEncoding('utf8')
if( res.headers['content-encoding'] == 'gzip' ) {
var gzip = zlib.createGunzip();
res.pipe(gzip);
outputBuffer = gzip;
} else {
outputBuffer = res;
}
outputBuffer.setEncoding('utf8')
//res.setEncoding('utf8')
outputBuffer.on('data', function (data) {
buffer2 += data.toString()
})
outputBuffer.on('end', function (d) {
/*** ByMahee -- commented the following block as the client and server doesn't have to be in publish and subscribe mode
//var md5hash = md5(thatmemento.originalURI) // urir cannot be passed in the raw
ConsoleLogIfRequired("-- By Mahee -- Inside On response end of http request of setSimhash")
ConsoleLogIfRequired("ByMahe -- here is the buffer content of " +mOptions.host+mOptions.path+":") */
// ConsoleLogIfRequired(buffer2)
// ConsoleLogIfRequired("========================================================")
//ConsoleLogIfRequired("Buffer Length ("+mOptions.host + mOptions.path +"):-> "+ buffer2.length)
if (buffer2.indexOf('Got an HTTP 302 response at crawl time') === -1 && thatmemento.simhash != '00000000') {
var sh = simhash((buffer2).split('')).join('')
ConsoleLogIfRequired("ByMahee -- computed simhash for "+mOptions.host+mOptions.path+" -> "+ sh)
var retStr = getHexString(sh)
if (!retStr || retStr === Memento.prototype.simhashIndicatorForHTTP302) {
// Normalize so not undefined
retStr = Memento.prototype.simhashIndicatorForHTTP302
// Gateway timeout from the archives, remove from consideration
// resolve('isA302DeleteMe')
callback()
}
buffer2 = ''
buffer2 = null
// ConsoleLogIfRequired("Hex Code for Simhash:"+retStr + ' & urir:' + mOptions.host + mOptions.path)
thatmemento.simhash = retStr
callback()
// resolve(retStr)
} else {
// We need to delete this memento, it's a duplicate and a "soft 302" from archive.org
callback()
//callback('isA302DeleteMe')
}
})
outputBuffer.on('error', function (err) {
ConsoleLogIfRequired('Error generating Simhash in Response')
})
})
req.on('error', function (err) {
ConsoleLogIfRequired('Error generating Simhash in Request')
ConsoleLogIfRequired(err)
callback()
// ConsoleLogIfRequired("-- By Mahee -- Inside On request error of http request of setSimhash")
})
req.end()
}
/**
* Given a URI, return a TimeMap from the Memento Aggregator
* TODO: God function that does WAY more than simply getting a timemap
* @param uri The urir in-question
*/
function getTimemapGodFunctionForAlSummarization (uri, response) {
ConsoleLogIfRequired("--ByMahee -- Inside function : getTimemapGodFunctionForAlSummarization")
ConsoleLogIfRequired("--ByMahee -- Applying AlSummarization on given urir = "+ uri)
// TODO: remove TM host and path references, they reside in the TM obj
/* ByMahee -- right now hitting only organization : web.archive.org , changing the following Host and Path to http://wayback.archive-it.org
*/
// var timemapHost = 'web.archive.org'
// var timemapPath = '/web/timemap/link/' + uri
var timemapHost = 'wayback.archive-it.org'
var timemapPath = '/'+collectionIdentifier+'/timemap/link/' + uri
if(primeSrc == 2 ){
timemapHost = 'web.archive.org'
timemapPath = '/web/timemap/link/' + uri
}else if(primeSrc == 3){ // must contain the Host and Path for Memento Aggregator
ConsoleLogIfRequired("Haven't given the Memgators Host and Path yet")
return
}
var options = {
'host': timemapHost,
'path': timemapPath,
'port': 80,
'method': 'GET'
}
ConsoleLogIfRequired('Path: ' + options.host + options.path)
var buffer = '' // An out-of-scope string to save the Timemap string, TODO: better documentation
var t
var mergedMementoArry = []
var retStr = ''
var metadata = ''
var uri2 ="https://www.epa.gov/smartway/smartway-sustainability-accounting-and-reporting" // needed if mementos from the redirected URI have to be merged
//var uri2 = "";
ConsoleLogIfRequired('Starting many asynchronous operationsX...')
async.series([
// TODO: define how this is different from the getTimemap() parent function (i.e., some name clarification is needed)
// TODO: abstract this method to its callback form. Currently, this is reaching and populating the timemap out of scope and can't be simply isolated (I tried)
function fetchTimemap (callback) {
var req = http.request(options, function (res) {
ConsoleLogIfRequired("--ByMahee-- Inside the http request call back success, request is made on the following obect:")
// ConsoleLogIfRequired(options);
// ConsoleLogIfRequired("----------------");
res.setEncoding('utf8')
res.on('data', function (data) {
buffer += data.toString()
})
res.on('end', function (d) {
// ConsoleLogIfRequired("Data Response from fetchTimeMap:" + buffer)
if (buffer.length > 100) { // Magic number = arbitrary, has be quantified for correctness
//ConsoleLogIfRequired('Timemap acquired for ' + uri + ' from ' + timemapHost + timemapPath)
// ConsoleLogIfRequired("-----------ByMahee--------")
// ConsoleLogIfRequired(buffer)
// ConsoleLogIfRequired("-----------ByMahee--------")
t = new TimeMap(buffer)
t.originalURI = uri // Need this for a filename for caching
t.createMementos()
ConsoleLogIfRequired("-- ByMahee -- Mementos are created by this point, following is the whole timeMap Object")
ConsoleLogIfRequired(t);
ConsoleLogIfRequired("---------------------------------------------------")
mergedMementoArry = mergedMementoArry.concat(t.mementos);
if (t.mementos.length === 0) {
ConsoleLogIfRequired('There were no mementos for ' + uri + ' :(')
response.write('There were no mementos for ' + uri + ' :(')
response.end()
return
}
// to respond to the client as the intermediate response, while the server processes huge loads
if(t.mementos.length > 250){
response.write('Request being processed, Please retry approximately after ( ' + ((t.mementos.length/50) * 10)/60 +' Minutes ) and request again...')
response.end()
isResponseEnded = true
}
ConsoleLogIfRequired('Fetching HTML for ' + t.mementos.length + ' mementos.')
callback('')
}else{
ConsoleLogIfRequired('The page you requested has not been archived.')
//process.exit(-1)
response.write('The page you requested has not been archived.')
response.end()
return
}
})
})
req.on('error', function (e) { // Houston...
ConsoleLogIfRequired('problem with request: ' + e.message)
ConsoleLogIfRequired(e)
if (e.message === 'connect ETIMEDOUT') { // Error experienced when IA went down on 20141211
ConsoleLogIfRequired('Hmm, the connection timed out. Internet Archive might be down.')
response.write('Hmm, the connection timed out. Internet Archive might be down.')
response.end()
return
}
})
req.on('socket', function (socket) { // Slow connection is slow
/*socket.setTimeout(3000)
socket.on('timeout', function () {
ConsoleLogIfRequired("The server took too long to respond and we're only getting older so we aborted.")
req.abort()
}) */
})
req.end()
},
function fetchTimemap2 (callback) {
if(uri2 == ""){
callback('')
}
var timemapHost = 'web.archive.org'
var timemapPath = '/web/timemap/link/' + uri2
var buffer ="";
var options = {
'host': timemapHost,
'path': timemapPath,
'port': 80,
'method': 'GET'
}
var req = http.request(options, function (res) {
ConsoleLogIfRequired("--ByMahee-- Inside the http request call back success, request is made on the following obect:")
// ConsoleLogIfRequired(options);
// ConsoleLogIfRequired("----------------");
res.setEncoding('utf8')
res.on('data', function (data) {
buffer += data.toString()
})
res.on('end', function (d) {
// ConsoleLogIfRequired("Data Response from fetchTimeMap:" + buffer)
if (buffer.length > 100) { // Magic number = arbitrary, has be quantified for correctness
//ConsoleLogIfRequired('Timemap acquired for ' + uri + ' from ' + timemapHost + timemapPath)
// ConsoleLogIfRequired("-----------ByMahee--------")
// ConsoleLogIfRequired(buffer)
// ConsoleLogIfRequired("-----------ByMahee--------")
t = new TimeMap(buffer)
t.originalURI = uri // Need this for a filename for caching
t.createMementos()
ConsoleLogIfRequired("-- ByMahee -- Mementos are created by this point, following is the whole timeMap Object")
ConsoleLogIfRequired(t.mementos);
ConsoleLogIfRequired("---------------------------------------------------")
mergedMementoArry = mergedMementoArry.concat(t.mementos);
mergedMementoArry.sort(function(m1, m2){ // sort object by datetime field
return ((new Date(m1["datetime"])).getTime()-(new Date(m2["datetime"])).getTime())
})
t.mementos = mergedMementoArry;
console.log("========================== Modified Merged array =====================")
console.log(JSON.stringify(t.mementos))
console.log("======================================================================")
if (t.mementos.length === 0) {
ConsoleLogIfRequired('There were no mementos for ' + uri + ' :(')
response.write('There were no mementos for ' + uri + ' :(')
response.end()
return
}
//ConsoleLogIfRequired('Fetching HTML for ' + t.mementos.length + ' mementos.')
callback('')
}else{
ConsoleLogIfRequired('The page you requested has not been archived.')
// response.write('The page you requested has not been archived.')
// response.end()
return
}
})
})
req.on('error', function (e) { // Houston...
ConsoleLogIfRequired('problem with request: ' + e.message)
ConsoleLogIfRequired(e)
if (e.message === 'connect ETIMEDOUT') { // Error experienced when IA went down on 20141211
ConsoleLogIfRequired('Hmm, the connection timed out. Internet Archive might be down.')
// response.write('Hmm, the connection timed out. Internet Archive might be down.')
// response.end()
return
}
})
req.on('socket', function (socket) { // Slow connection is slow
/*socket.setTimeout(3000)
socket.on('timeout', function () {
ConsoleLogIfRequired("The server took too long to respond and we're only getting older so we aborted.")
req.abort()
}) */
})
req.end()
},
//ByMahee -- commented out some of the methods called to build step by step
/* **
// TODO: remove this function from callback hell
function (callback) {t.printMementoInformation(response, callback, false);}, // Return blank UI ASAP */
// -- ByMahee -- Uncomment one by one for CLI_JSON
function (callback) {t.calculateSimhashes(callback);},
function (callback) {t.saveSimhashesToCache(callback);},
function (callback) {
if(isToComputeBoth){
t.calculateHammingDistancesWithOnlineFiltering(callback);
}
else if (callback) {
callback('')
}
},
function (callback) {
if(isToComputeBoth){
t.supplyChosenMementosBasedOnHammingDistanceAScreenshotURI(callback);
}
else if (callback) {
callback('')
}
},
function (callback) {t.writeJSONToCache(callback)},
function (callback) {
if(isToComputeBoth){
t.createScreenshotsForMementos(response,callback);
}
else if (callback) {
callback('')
}
},
function (callback) {t.writeThumbSumJSONOPToCache(response,callback)}
],
function (err, result) {
if (err) {
ConsoleLogIfRequired('ERROR!')
ConsoleLogIfRequired(err)
} else {
ConsoleLogIfRequired('There were no errors executing the callback chain')
}
})
// Fisher-Yates shuffle per http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array
function getRandomSubsetOfMementosArray (arr,siz) {
var shuffled = arr.slice(0)
var i = arr.length
var temp
var index
while (i--) {
index = Math.floor((i + 1) * Math.random())
temp = shuffled[index]
shuffled[index] = shuffled[i]
shuffled[i] = temp
}
return shuffled.slice(0, size)
}
function getTimeDiffBetweenTwoMementoURIs (newerMementoURI, olderMementoURI) {
var newerDate = newerMementoURI.match(/[0-9]{14}/g)[0] // Newer
var olderDate = olderMementoURI.match(/[0-9]{14}/g)[0] // Older
if (newerDate && olderDate) {
try {
var diff = (parseInt(newerDate) - parseInt(olderDate))
return diff
}catch (e) {
ConsoleLogIfRequired(e.message)
}
} else {
throw new Exception('Both mementos in comparison do not have encoded datetimes in the URIs:\r\n\t' + newerMemento.uri + '\r\n\t' + olderMemento.uri)
}
}
} /* End God Function */
/*****************************************
// SUPPLEMENTAL TIMEMAP FUNCTIONALITY
***************************************** */
TimeMap.prototype.calculateSimhashes = function (callback) {
//ConsoleLogIfRequired("--- By Mahee - For my understanding")
//ConsoleLogIfRequired("Inside CalculateSimhashes")
var theTimeMap = this
var arrayOfSetSimhashFunctions = []
// the way to get a damper, just 7 requests at a time.
async.eachLimit(this.mementos,7, function(curMemento, callback){
curMemento.setSimhash(callback)
// ConsoleLogIfRequired(curMemento)
}, function(err) {
// ConsoleLogIfRequired("length of arrayOfSetSimhashFunctions: -> " + arrayOfSetSimhashFunctions.length);
if(err){
ConsoleLogIfRequired("Inside async Each Limit")
ConsoleLogIfRequired(err)
return
}
// ConsoleLogIfRequired("After all the resquests are resolved, theTimemap -> "+ theTimeMap)
ConsoleLogIfRequired('Checking if there are mementos to remove')
var mementosRemoved = 0
ConsoleLogIfRequired('About to go into loop of ## mementos: ' + (theTimeMap.mementos.length - 1))
// Remove all mementos whose payload body was a Wayback soft 302
for (var i = theTimeMap.mementos.length - 1; i >= 0; i--) {
/* if (theTimemap.mementos[i].simhash === 'isA302DeleteMe') { //this was the original conetent of the code,
* according to my understanding 'theTimemap.mementos[i].simhash' has to be checked with 'Memento.prototype.simhashIndicatorForHTTP302',
* doing the same: just changed the above condition as to follow
*/
if(theTimeMap.mementos[i].simhash === Memento.prototype.simhashIndicatorForHTTP302){
theTimeMap.mementos.splice(i, 1)
mementosRemoved++
}
}
// console.timeEnd('simhashing')
ConsoleLogIfRequired(mementosRemoved + ' mementos removed due to Wayback "soft 3xxs"')
if (callback) {
callback('')
}
})
}
TimeMap.prototype.saveSimhashesToCache = function (callback,format) {
// TODO: remove dependency on global timemap t
var strToWrite = ''
for (var m = 0; m < this.mementos.length; m++) {
if (this.mementos[m].simhash != Memento.prototype.simhashIndicatorForHTTP302) {
strToWrite += this.mementos[m].simhash + ' ' + this.mementos[m].uri + ' ' + this.mementos[m].datetime + '\r\n'
}
}
ConsoleLogIfRequired('Done getting simhashes from array')
ConsoleLogIfRequired('-- ByMahee -- In function SaveSimhashesToCache -- Simhash for URI and DateTime is as follows:')
ConsoleLogIfRequired(strToWrite)
ConsoleLogIfRequired("-------------------------------------------------------------------------")
var cacheFile = new SimhashCacheFile(primeSource+"_"+collectionIdentifier+"_"+this.originalURI,isDebugMode)
cacheFile.replaceContentWith(strToWrite)
if (callback) {
callback('')
}
}
TimeMap.prototype.writeJSONToCache = function (callback) {
var cacheFile = new SimhashCacheFile(primeSource+"_"+collectionIdentifier+"_"+this.originalURI,isDebugMode)
cacheFile.writeFileContentsAsJSON(this.mementos)
console.log(JSON.stringify(this.mementos));
if (callback) {
callback('')
}
}
/**
* Constructs the JSON in the needed format and sends it over to Client, this method is called only if the request comes from a Cached mode
*/
TimeMap.prototype.SendThumbSumJSONCalledFromCache= function (response,callback) {
var month_names_short= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var mementoJObjArrForTimeline=[];
var mementoJObjArrFor_Grid_Slider =[];
// Assuming foreach is faster than for-i, this can be executed out-of-order
this.mementos.forEach(function (memento,m) {
var uri = memento.uri
// need to have the following line, id_ isnot needed for screen shot, to replace /12345678912345id_/ to /12345678912345/
var regExpForDTStr = /\/\d{14}id_\// // to match something lile /12345678912345id_/
var matchedString = uri.match(regExpForDTStr)
if(matchedString != null){
uri = uri.replace(matchedString[0],(matchedString[0].toString().replace("id_",""))) // by default only the first occurance is replaced
}
// this is been replaced by the above so as not to have any clashes
//uri = uri.replace("id_/http","/http");
var mementoJObj_ForTimeline ={}
var mementoJObj_ForGrid_Slider={}
var dt = new Date(memento["datetime"].split(",")[1])
var date = dt.getDate()
var month = dt.getMonth() + 1
if(date <10){
date = "0"+date
}
if(month < 10){
month = "0"+month
}
var eventDisplayDate = dt.getUTCFullYear()+"-"+ month+"-"+date+", "+ memento["datetime"].split(" ")[4]
mementoJObj_ForTimeline["timestamp"] = Number(dt)/1000
if(memento.screenshotURI == null || memento.screenshotURI==''){
mementoJObj_ForTimeline["event_series"] = "Non-Thumbnail Mementos"
mementoJObj_ForTimeline["event_html"] = localAssetServer+"notcaptured.png"
mementoJObj_ForTimeline["event_html_similarto"] = localAssetServer+memento.hammingBasisScreenshotURI
}else{
var filename = 'timemapSum_' + uri.replace(/[^a-z0-9]/gi, '').toLowerCase() + '.png' // Sanitize URI->filename
mementoJObj_ForTimeline["event_series"] = "Thumbnails"
mementoJObj_ForTimeline["event_html"] = localAssetServer+memento.screenshotURI
}