forked from linkeddata/rdflib.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.js
1867 lines (1709 loc) · 69 KB
/
web.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
/**
*
* Project: rdflib.js, originally part of Tabulator project
*
* File: web.js
*
* Description: contains functions for requesting/fetching/retracting
* This implements quite a lot of the web architecture.
* A fetcher is bound to a specific knowledge base graph, into which
* it loads stuff and into which it writes its metadata
* @@ The metadata should be optionally a separate graph
*
* - implements semantics of HTTP headers, Internet Content Types
* - selects parsers for rdf/xml, n3, rdfa, grddl
*
* Dependencies:
*
* needs: util.js uri.js term.js rdfparser.js rdfa.js n3parser.js
* identity.js sparql.js jsonparser.js
*
* If jQuery is defined, it uses jQuery.ajax, else is independent of jQuery
*/
/**
* Things to test: callbacks on request, refresh, retract
* loading from HTTP, HTTPS, FTP, FILE, others?
* To do:
* Firing up a mail client for mid: (message:) URLs
*/
var asyncLib = require('async')
var jsonld = require('jsonld')
var N3 = require('n3')
$rdf.Fetcher = function (store, timeout, async) {
this.store = store
this.thisURI = 'http://dig.csail.mit.edu/2005/ajar/ajaw/rdf/sources.js' + '#SourceFetcher' // -- Kenny
this.timeout = timeout ? timeout : 30000
this.async = async != null ? async : true
this.appNode = this.store.bnode() // Denoting this session
this.store.fetcher = this // Bi-linked
this.requested = {}
// this.requested[uri] states:
// undefined no record of web access or records reset
// true has been requested, XHR in progress
// 'done' received, Ok
// 403 HTTP status unauthorized
// 404 Ressource does not exist. Can be created etc.
// 'redirected' In attempt to counter CORS problems retried.
// other strings mean various other erros, such as parse errros.
//
this.fetchCallbacks = {} // fetchCallbacks[uri].push(callback)
this.nonexistant = {} // keep track of explict 404s -> we can overwrite etc
this.lookedUp = {}
this.handlers = []
this.mediatypes = {}
var sf = this
var kb = this.store
var ns = {} // Convenience namespaces needed in this module:
// These are delibertely not exported as the user application should
// make its own list and not rely on the prefixes used here,
// and not be tempted to add to them, and them clash with those of another
// application.
ns.link = $rdf.Namespace('http://www.w3.org/2007/ont/link#')
ns.http = $rdf.Namespace('http://www.w3.org/2007/ont/http#')
ns.httph = $rdf.Namespace('http://www.w3.org/2007/ont/httph#')
ns.rdf = $rdf.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
ns.rdfs = $rdf.Namespace('http://www.w3.org/2000/01/rdf-schema#')
ns.dc = $rdf.Namespace('http://purl.org/dc/elements/1.1/')
$rdf.Fetcher.crossSiteProxy = function (uri) {
if ($rdf.Fetcher.crossSiteProxyTemplate) {
return $rdf.Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri))
} else {
return undefined
}
}
$rdf.Fetcher.RDFXMLHandler = function (args) {
if (args) {
this.dom = args[0]
}
this.handlerFactory = function (xhr) {
xhr.handle = function (cb) {
// sf.addStatus(xhr.req, 'parsing soon as RDF/XML...')
var kb = sf.store
if (!this.dom) this.dom = $rdf.Util.parseXML(xhr.responseText)
var root = this.dom.documentElement
if (root.nodeName === 'parsererror') { // @@ Mozilla only See issue/issue110
sf.failFetch(xhr, 'Badly formed XML in ' + xhr.resource.uri) // have to fail the request
throw new Error('Badly formed XML in ' + xhr.resource.uri) // @@ Add details
}
// Find the last URI we actual URI in a series of redirects
// (xhr.resource.uri is the original one)
var lastRequested = kb.any(xhr.req, ns.link('requestedURI'))
if (!lastRequested) {
lastRequested = xhr.resource
} else {
lastRequested = kb.sym(lastRequested.value)
}
var parser = new $rdf.RDFParser(kb)
// sf.addStatus(xhr.req, 'parsing as RDF/XML...')
parser.parse(this.dom, lastRequested.uri, lastRequested)
if (!xhr.options.noMeta) {
kb.add(lastRequested, ns.rdf('type'), ns.link('RDFDocument'), sf.appNode)
}
cb()
}
}
}
$rdf.Fetcher.RDFXMLHandler.toString = function () {
return 'RDFXMLHandler'
}
$rdf.Fetcher.RDFXMLHandler.register = function (sf) {
sf.mediatypes['application/rdf+xml'] = {}
}
$rdf.Fetcher.RDFXMLHandler.pattern = new RegExp('application/rdf\\+xml')
// This would much better use on-board XSLT engine. @@
/* deprocated 2016-02-17 timbl
$rdf.Fetcher.doGRDDL = function(kb, doc, xslturi, xmluri) {
sf.requestURI('http://www.w3.org/2005/08/' + 'online_xslt/xslt?' + 'xslfile=' + escape(xslturi) + '&xmlfile=' + escape(xmluri), doc)
}
*/
$rdf.Fetcher.XHTMLHandler = function (args) {
if (args) {
this.dom = args[0]
}
this.handlerFactory = function (xhr) {
xhr.handle = function (cb) {
var relation, reverse
if (!this.dom) {
this.dom = $rdf.Util.parseXML(xhr.responseText)
}
var kb = sf.store
// dc:title
var title = this.dom.getElementsByTagName('title')
if (title.length > 0) {
kb.add(xhr.resource, ns.dc('title'), kb.literal(title[0].textContent), xhr.resource)
// $rdf.log.info("Inferring title of " + xhr.resource)
}
// link rel
var links = this.dom.getElementsByTagName('link')
for (var x = links.length - 1; x >= 0; x--) { // @@ rev
relation = links[x].getAttribute('rel')
reverse = false
if (!relation) {
relation = links[x].getAttribute('rev')
reverse = true
}
if (relation) {
sf.linkData(xhr, relation,
links[x].getAttribute('href'), xhr.resource, reverse)
}
}
// Data Islands
var scripts = this.dom.getElementsByTagName('script')
for (var i = 0; i < scripts.length; i++) {
var contentType = scripts[i].getAttribute('type')
if ($rdf.parsable[contentType]) {
$rdf.parse(scripts[i].textContent, kb, xhr.resource.uri, contentType)
}
}
// GRDDL
/*
var head = this.dom.getElementsByTagName('head')[0]
if (head) {
var profile = head.getAttribute('profile')
if (profile && $rdf.uri.protocol(profile) === 'http') {
// $rdf.log.info("GRDDL: Using generic " + "2003/11/rdf-in-xhtml-processor.")
$rdf.Fetcher.doGRDDL(kb, xhr.resource, "http://www.w3.org/2003/11/rdf-in-xhtml-processor", xhr.resource.uri)
} else {
// $rdf.log.info("GRDDL: No GRDDL profile in " + xhr.resource)
}
}
*/
if (!xhr.options.noMeta) {
kb.add(xhr.resource, ns.rdf('type'), ns.link('WebPage'), sf.appNode)
}
// Do RDFa here
if ($rdf.parseDOM_RDFa) {
$rdf.parseDOM_RDFa(this.dom, kb, xhr.resource.uri)
}
cb() // Fire done callbacks
}
}
}
$rdf.Fetcher.XHTMLHandler.toString = function () {
return 'XHTMLHandler'
}
$rdf.Fetcher.XHTMLHandler.register = function (sf) {
sf.mediatypes['application/xhtml+xml'] = {
'q': 0.3
}
}
$rdf.Fetcher.XHTMLHandler.pattern = new RegExp('application/xhtml')
$rdf.Fetcher.XMLHandler = function () {
this.handlerFactory = function (xhr) {
xhr.handle = function (cb) {
var kb = sf.store
var dom = $rdf.Util.parseXML(xhr.responseText)
// XML Semantics defined by root element namespace
// figure out the root element
for (var c = 0; c < dom.childNodes.length; c++) {
// is this node an element?
if (dom.childNodes[c].nodeType === 1) {
// We've found the first element, it's the root
var ns = dom.childNodes[c].namespaceURI
// Is it RDF/XML?
if (ns && ns === ns['rdf']) {
sf.addStatus(xhr.req, 'Has XML root element in the RDF namespace, so assume RDF/XML.')
sf.switchHandler('RDFXMLHandler', xhr, cb, [dom])
return
}
// it isn't RDF/XML or we can't tell
// Are there any GRDDL transforms for this namespace?
// @@ assumes ns documents have already been loaded
/*
var xforms = kb.each(kb.sym(ns), kb.sym("http://www.w3.org/2003/g/data-view#namespaceTransformation"))
for (var i = 0; i < xforms.length; i++) {
var xform = xforms[i]
// $rdf.log.info(xhr.resource.uri + " namespace " + ns + " has GRDDL ns transform" + xform.uri)
$rdf.Fetcher.doGRDDL(kb, xhr.resource, xform.uri, xhr.resource.uri)
}
*/
break
}
}
// Or it could be XHTML?
// Maybe it has an XHTML DOCTYPE?
if (dom.doctype) {
// $rdf.log.info("We found a DOCTYPE in " + xhr.resource)
if (dom.doctype.name === 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) {
sf.addStatus(xhr.req, 'Has XHTML DOCTYPE. Switching to XHTML Handler.\n')
sf.switchHandler('XHTMLHandler', xhr, cb)
return
}
}
// Or what about an XHTML namespace?
var html = dom.getElementsByTagName('html')[0]
if (html) {
var xmlns = html.getAttribute('xmlns')
if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) {
sf.addStatus(xhr.req, 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\n')
sf.switchHandler('XHTMLHandler', xhr, cb)
return
}
}
// At this point we should check the namespace document (cache it!) and
// look for a GRDDL transform
// @@ Get namespace document <n>, parse it, look for <n> grddl:namespaceTransform ?y
// Apply ?y to dom
// We give up. What dialect is this?
sf.failFetch(xhr, 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n' + xhr.responseText.slice(0, 80))
}
}
}
$rdf.Fetcher.XMLHandler.toString = function () {
return 'XMLHandler'
}
$rdf.Fetcher.XMLHandler.register = function (sf) {
sf.mediatypes['text/xml'] = {
'q': 0.2
}
sf.mediatypes['application/xml'] = {
'q': 0.2
}
}
$rdf.Fetcher.XMLHandler.pattern = new RegExp('(text|application)/(.*)xml')
$rdf.Fetcher.HTMLHandler = function () {
this.handlerFactory = function (xhr) {
xhr.handle = function (cb) {
var rt = xhr.responseText
// We only handle XHTML so we have to figure out if this is XML
// $rdf.log.info("Sniffing HTML " + xhr.resource + " for XHTML.")
if (rt.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)) {
sf.addStatus(xhr.req, "Has an XML declaration. We'll assume " +
"it's XHTML as the content-type was text/html.\n")
sf.switchHandler('XHTMLHandler', xhr, cb)
return
}
// DOCTYPE
// There is probably a smarter way to do this
if (rt.match(/.*<!DOCTYPE\s+html[^<]+-\/\/W3C\/\/DTD XHTML[^<]+http:\/\/www.w3.org\/TR\/xhtml[^<]+>/)) {
sf.addStatus(xhr.req, 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n')
sf.switchHandler('XHTMLHandler', xhr, cb)
return
}
// xmlns
if (rt.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/)) {
sf.addStatus(xhr.req, 'Has default namespace for XHTML, so switching to XHTMLHandler.\n')
sf.switchHandler('XHTMLHandler', xhr, cb)
return
}
// dc:title //no need to escape '/' here
var titleMatch = (new RegExp('<title>([\\s\\S]+?)</title>', 'im')).exec(rt)
if (titleMatch) {
var kb = sf.store
kb.add(
xhr.resource,
ns.dc('title'),
kb.literal(titleMatch[1]),
xhr.resource
) // think about xml:lang later
kb.add(xhr.resource, ns.rdf('type'), ns.link('WebPage'), sf.appNode)
cb() // doneFetch, not failed
return
}
sf.failFetch(xhr, "Sorry, can't yet parse non-XML HTML")
}
}
}
$rdf.Fetcher.HTMLHandler.toString = function () {
return 'HTMLHandler'
}
$rdf.Fetcher.HTMLHandler.register = function (sf) {
sf.mediatypes['text/html'] = {
'q': 0.3
}
}
$rdf.Fetcher.HTMLHandler.pattern = new RegExp('text/html')
$rdf.Fetcher.TextHandler = function () {
this.handlerFactory = function (xhr) {
xhr.handle = function (cb) {
// We only speak dialects of XML right now. Is this XML?
var rt = xhr.responseText
// Look for an XML declaration
if (rt.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)) {
sf.addStatus(xhr.req, 'Warning: ' + xhr.resource + " has an XML declaration. We'll assume " +
"it's XML but its content-type wasn't XML.\n")
sf.switchHandler('XMLHandler', xhr, cb)
return
}
// Look for an XML declaration
if (rt.slice(0, 500).match(/xmlns:/)) {
sf.addStatus(xhr.req, "May have an XML namespace. We'll assume " +
"it's XML but its content-type wasn't XML.\n")
sf.switchHandler('XMLHandler', xhr, cb)
return
}
// We give up finding semantics - this is not an error, just no data
sf.addStatus(xhr.req, 'Plain text document, no known RDF semantics.')
sf.doneFetch(xhr, [xhr.resource.uri])
// sf.failFetch(xhr, "unparseable - text/plain not visibly XML")
// dump(xhr.resource + " unparseable - text/plain not visibly XML, starts:\n" + rt.slice(0, 500)+"\n")
}
}
}
$rdf.Fetcher.TextHandler.toString = function () {
return 'TextHandler'
}
$rdf.Fetcher.TextHandler.register = function (sf) {
sf.mediatypes['text/plain'] = {
'q': 0.1
}
}
$rdf.Fetcher.TextHandler.pattern = new RegExp('text/plain')
$rdf.Fetcher.N3Handler = function () {
this.handlerFactory = function (xhr) {
xhr.handle = function (cb) {
// Parse the text of this non-XML file
$rdf.log.debug('web.js: Parsing as N3 ' + xhr.resource.uri) // @@@@ comment me out
// sf.addStatus(xhr.req, "N3 not parsed yet...")
var rt = xhr.responseText
var p = $rdf.N3Parser(kb, kb, xhr.resource.uri, xhr.resource.uri, null, null, '', null)
// p.loadBuf(xhr.responseText)
try {
p.loadBuf(xhr.responseText)
} catch (e) {
var msg = ('Error trying to parse ' + xhr.resource + ' as Notation3:\n' + e + ':\n' + e.stack)
// dump(msg+"\n")
sf.failFetch(xhr, msg)
return
}
sf.addStatus(xhr.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.')
sf.store.add(xhr.resource, ns.rdf('type'), ns.link('RDFDocument'), sf.appNode)
args = [xhr.resource.uri] // Other args needed ever?
sf.doneFetch(xhr, args)
}
}
}
$rdf.Fetcher.N3Handler.toString = function () {
return 'N3Handler'
}
$rdf.Fetcher.N3Handler.register = function (sf) {
sf.mediatypes['text/n3'] = {
'q': '1.0'
} // as per 2008 spec
sf.mediatypes['application/x-turtle'] = {
'q': 1.0
} // pre 2008
sf.mediatypes['text/turtle'] = {
'q': 1.0
} // pre 2008
}
$rdf.Fetcher.N3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\+)?(n3|turtle)')
$rdf.Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', 'refresh', 'retract', 'done'])
this.addHandler = function (handler) {
sf.handlers.push(handler)
handler.register(sf)
}
this.switchHandler = function (name, xhr, cb, args) {
var kb = this.store
var handler = null
for (var i = 0; i < this.handlers.length; i++) {
if ('' + this.handlers[i] === name) {
handler = this.handlers[i]
}
}
if (!handler) {
throw new Error('web.js: switchHandler: name=' + name + ' , this.handlers =' + this.handlers + '\n' +
'switchHandler: switching to ' + handler + '; sf=' + sf +
'; typeof $rdf.Fetcher=' + typeof $rdf.Fetcher +
';\n\t $rdf.Fetcher.HTMLHandler=' + $rdf.Fetcher.HTMLHandler + '\n' +
'\n\tsf.handlers=' + sf.handlers + '\n')
}
(new handler(args)).handlerFactory(xhr)
xhr.handle(cb)
}
this.addStatus = function (req, status) {
// <Debug about="parsePerformance">
var now = new Date()
status = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() + '] ' + status
// </Debug>
var kb = this.store
var s = kb.the(req, ns.link('status'))
if (s && s.append) {
s.append(kb.literal(status))
} else {
$rdf.log.warn('web.js: No list to add to: ' + s + ',' + status) // @@@
}
}
// Record errors in the system on failure
// Returns xhr so can just do return this.failfetch(...)
this.failFetch = function (xhr, status) {
this.addStatus(xhr.req, status)
if (!xhr.options.noMeta) {
kb.add(xhr.resource, ns.link('error'), status)
}
this.requested[$rdf.uri.docpart(xhr.resource.uri)] = xhr.status // changed 2015 was false
while (this.fetchCallbacks[xhr.resource.uri] && this.fetchCallbacks[xhr.resource.uri].length) {
this.fetchCallbacks[xhr.resource.uri].shift()(false, 'Fetch of <' + xhr.resource.uri + '> failed: ' + status, xhr)
}
delete this.fetchCallbacks[xhr.resource.uri]
this.fireCallbacks('fail', [xhr.requestedURI, status])
xhr.abort()
return xhr
}
// in the why part of the quad distinguish between HTML and HTTP header
// Reverse is set iif the link was rev= as opposed to rel=
this.linkData = function (xhr, rel, uri, why, reverse) {
var x = xhr.resource
if (!uri) return
var predicate
// See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10
var obj = kb.sym($rdf.uri.join(uri, xhr.resource.uri))
if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' || rel === 'describedby') {
if (obj.uri === xhr.resource.uri) return
predicate = ns.rdfs('seeAlso')
} else if (rel === 'type') {
predicate = tabulator.ns.rdf('type')
} else {
// See https://www.iana.org/assignments/link-relations/link-relations.xml
// Alas not yet in RDF yet for each predicate
predicate = kb.sym($rdf.uri.join(rel, 'http://www.iana.org/assignments/link-relations/'))
}
if (reverse) {
kb.add(obj, predicate, xhr.resource, why)
} else {
kb.add(xhr.resource, predicate, obj, why)
}
}
this.parseLinkHeader = function (xhr, thisReq) {
var link
try {
link = xhr.getResponseHeader('link') // May crash from CORS error
} catch (e) {}
if (link) {
var linkexp = /<[^>]*>\s*(\s*;\s*[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g
var paramexp = /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g
var matches = link.match(linkexp)
var rels = {}
for (var i = 0; i < matches.length; i++) {
var split = matches[i].split('>')
var href = split[0].substring(1)
var ps = split[1]
var s = ps.match(paramexp)
for (var j = 0; j < s.length; j++) {
var p = s[j]
var paramsplit = p.split('=')
// var name = paramsplit[0]
var rel = paramsplit[1].replace(/["']/g, '') // '"
this.linkData(xhr, rel, href, thisReq)
}
}
}
}
this.doneFetch = function (xhr, args) {
this.addStatus(xhr.req, 'Done.')
// $rdf.log.info("Done with parse, firing 'done' callbacks for " + xhr.resource)
this.requested[xhr.resource.uri] = 'done' // Kenny
while (this.fetchCallbacks[xhr.resource.uri] && this.fetchCallbacks[xhr.resource.uri].length) {
this.fetchCallbacks[xhr.resource.uri].shift()(true, undefined, xhr)
}
delete this.fetchCallbacks[xhr.resource.uri]
this.fireCallbacks('done', args)
}
var handlerList = [
$rdf.Fetcher.RDFXMLHandler, $rdf.Fetcher.XHTMLHandler,
$rdf.Fetcher.XMLHandler, $rdf.Fetcher.HTMLHandler,
$rdf.Fetcher.TextHandler, $rdf.Fetcher.N3Handler
]
handlerList.map(this.addHandler)
/** Note two nodes are now smushed
**
** If only one was flagged as looked up, then
** the new node is looked up again, which
** will make sure all the URIs are dereferenced
*/
this.nowKnownAs = function (was, now) {
if (this.lookedUp[was.uri]) {
if (!this.lookedUp[now.uri]) this.lookUpThing(now, was) // @@@@ Transfer userCallback
} else if (this.lookedUp[now.uri]) {
if (!this.lookedUp[was.uri]) this.lookUpThing(was, now)
}
}
// Returns promise of XHR
//
this.webOperation = function (method, uri, options) {
uri = uri.uri || uri; options = options || {}
var fetcher = this
return new Promise(function (resolve, reject) {
var xhr = $rdf.Util.XMLHTTPFactory()
xhr.options = options
if (!options.noMeta) {
fetcher.saveRequestMetadata(xhr, tabulator.kb, uri)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // NOte a 404 can be not afailure
var ok = (!xhr.status || (xhr.status >= 200 && xhr.status < 300))
if (!options.noMeta) {
var response = fetcher.saveResponseMetadata(xhr, tabulator.kb)
}
if (ok) resolve(xhr)
reject(xhr.status + ' ' + xhr.statusText)
}
}
xhr.open(method, uri, true)
if (options.contentType) {
xhr.setRequestHeader('Content-type', options.contentType)
}
xhr.send(options.data ? options.data : undefined)
})
}
this.webCopy = function (here, there, content_type) {
var fetcher = this
here = here.uri || here
return new Promise(function (resolve, reject) {
this.webOperation('GET', here)
.then(function (xhr) {
fetcher.webOperation('PUT', // @@@ change to binary from text
there, { data: xhr.responseText, contentType: content_type })
})
.then(function (xhr) {
resolve(xhr)
})
.catch(function (e) {
reject(e)
})
})
}
// Looks up something.
//
// Looks up all the URIs a things has.
//
// Parameters:
//
// term: canonical term for the thing whose URI is to be dereferenced
// rterm: the resource which refered to this (for tracking bad links)
// options: (old: force paraemter) or dictionary of options:
// force: Load the data even if loaded before
// oneDone: is called as callback(ok, errorbody, xhr) for each one
// allDone: is called as callback(ok, errorbody) for all of them
// Returns the number of URIs fetched
//
this.lookUpThing = function (term, rterm, options, oneDone, allDone) {
var uris = kb.uris(term) // Get all URIs
var success = true
var errors = ''
var outstanding = {}
var force
if (options === false || options === true) { // Old signature
force = options
options = { force: force }
} else {
if (options === undefined) options = {}
force = !!options.force
}
if (typeof uris !== 'undefined') {
for (var i = 0; i < uris.length; i++) {
var u = uris[i]
outstanding[u] = true
this.lookedUp[u] = true
var sf = this
var requestOne = function requestOne (u1) {
sf.requestURI($rdf.uri.docpart(u1), rterm, options,
function (ok, body, xhr) {
if (ok) {
if (oneDone) oneDone(true, u1)
} else {
if (oneDone) oneDone(false, body)
success = false
errors += body + '\n'
}
delete outstanding[u]
if (Object.keys(outstanding).length > 0) {
return
}
if (allDone) {
allDone(success, errors)
}
}
)
}
requestOne(u)
}
}
return uris.length
}
/* Promise-based load function
**
** NamedNode -> Promise of xhr
** uri string -> Promise of xhr
** Array of the above -> Promise of array of xhr
**
** @@ todo: If p1 is array then sequence or parallel fetch of all
*/
this.load = function (uri, options) {
var fetcher = this
if (uri instanceof Array) {
var ps = uri.map(function (x) {
return fetcher.load(x)
})
return Promise.all(ps)
}
uri = uri.uri || uri // NamedNode or URI string
return new Promise(function (resolve, reject) {
fetcher.nowOrWhenFetched(uri, options, function (ok, message, xhr) {
if (ok) {
resolve(xhr)
} else {
reject(message)
}
})
})
}
/* Ask for a doc to be loaded if necessary then call back
**
** Changed 2013-08-20: Added (ok, errormessage) params to callback
**
** Calling methods:
** nowOrWhenFetched (uri, userCallback)
** nowOrWhenFetched (uri, options, userCallback)
** nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old
** nowOrWhenFetched (uri, referringTerm, userCallback) <-- old
**
** Options include:
** referringTerm The docuemnt in which this link was found.
** this is valuable when finding the source of bad URIs
** force boolean. Never mind whether you have tried before,
** load this from scratch.
** forceContentType Override the incoming header to force the data to be
** treaed as this content-type.
**/
this.nowOrWhenFetched = function (uri, p2, userCallback, options) {
uri = uri.uri || uri // allow symbol object or string to be passed
if (typeof p2 === 'function') {
options = {}
userCallback = p2
} else if (typeof p2 === 'undefined') { // original calling signature
referingTerm = undefined
} else if (p2 instanceof $rdf.NamedNode) {
referingTerm = p2
} else {
options = p2
}
this.requestURI(uri, p2, options || {}, userCallback)
}
this.get = this.nowOrWhenFetched
// Look up response header
//
// Returns: a list of header values found in a stored HTTP response
// or [] if response was found but no header found
// or undefined if no response is available.
//
this.getHeader = function (doc, header) {
var kb = this.store
var requests = kb.each(undefined, ns.link('requestedURI'), doc.uri)
for (var r = 0; r < requests.length; r++) {
var request = requests[r]
if (request !== undefined) {
var response = kb.any(request, ns.link('response'))
if (request !== undefined) {
var results = kb.each(response, ns.httph(header.toLowerCase()))
if (results.length) {
return results.map(function (v) {
return v.value
})
}
return []
}
}
}
return undefined
}
this.proxyIfNecessary = function (uri) {
if (typeof tabulator !== 'undefined' && tabulator.isExtension) return uri // Extenstion does not need proxy
// browser does 2014 on as https browser script not trusted
// If the web app origin is https: then the mixed content rules
// prevent it loading insecure http: stuff so we need proxy.
if ($rdf.Fetcher.crossSiteProxyTemplate &&
(typeof document !== 'undefined') &&
document.location &&
('' + document.location).slice(0, 6) === 'https:' && // origin is secure
uri.slice(0, 5) === 'http:') { // requested data is not
return $rdf.Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri))
}
return uri
}
this.saveRequestMetadata = function (xhr, kb, docuri) {
var request = kb.bnode()
xhr.resource = $rdf.sym(docuri)
xhr.req = request
if (!xhr.options.noMeta) { // Store no triples but do mind the bnode for req
var now = new Date()
var timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '] '
kb.add(request, ns.rdfs('label'), kb.literal(timeNow + ' Request for ' + docuri), this.appNode)
kb.add(request, ns.link('requestedURI'), kb.literal(docuri), this.appNode)
kb.add(request, ns.link('status'), kb.collection(), this.appNode)
}
return request
}
this.saveResponseMetadata = function (xhr, kb) {
var response = kb.bnode()
if (xhr.req) kb.add(xhr.req, ns.link('response'), response)
kb.add(response, ns.http('status'), kb.literal(xhr.status), response)
kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response)
xhr.headers = {}
if ($rdf.uri.protocol(xhr.resource.uri) === 'http' || $rdf.uri.protocol(xhr.resource.uri) === 'https') {
xhr.headers = $rdf.Util.getHTTPHeaders(xhr)
for (var h in xhr.headers) { // trim below for Safari - adds a CR!
kb.add(response, ns.httph(h.toLowerCase()), xhr.headers[h].trim(), response)
}
}
return response
}
/** Requests a document URI and arranges to load the document.
** Parameters:
** term: term for the thing whose URI is to be dereferenced
** rterm: the resource which refered to this (for tracking bad links)
** options:
** force: Load the data even if loaded before
** withCredentials: flag for XHR/CORS etc
** userCallback: Called with (true) or (false, errorbody, {status: 400}) after load is done or failed
** Return value:
** The xhr object for the HTTP access
** null if the protocol is not a look-up protocol,
** or URI has already been loaded
*/
this.requestURI = function (docuri, rterm, options, userCallback) { // sources_request_new
docuri = docuri.uri || docuri // NamedNode or string
// Remove #localid
docuri = docuri.split('#')[0]
if (typeof options === 'boolean') {
options = { 'force': options } // Ols dignature
}
if (typeof options === 'undefined') options = {}
var force = !!options.force
var kb = this.store
var args = arguments
var pcol = $rdf.uri.protocol(docuri)
if (pcol === 'tel' || pcol === 'mailto' || pcol === 'urn') {
// "No look-up operation on these, but they are not errors?"
return userCallback(false, 'Unsupported protocol', { 'status': 900 }) ||
undefined
}
var docterm = kb.sym(docuri)
var sta = this.getState(docuri)
if (!force) {
if (sta === 'fetched') {
return userCallback ? userCallback(true) : undefined
}
if (sta === 'failed') {
return userCallback
? userCallback(false, 'Previously failed. ' + this.requested[docuri],
{'status': this.requested[docuri]})
: undefined // An xhr standin
}
// if (sta === 'requested') return userCallback? userCallback(false, "Sorry already requested - pending already.", {'status': 999 }) : undefined
} else {
delete this.nonexistant[docuri]
}
// @@ Should allow concurrent requests
// If it is 'failed', then shoulkd we try again? I think so so an old error doens't get stuck
// if (sta === 'unrequested')
this.fireCallbacks('request', args) // Kenny: fire 'request' callbacks here
// dump( "web.js: Requesting uri: " + docuri + "\n" )
if (userCallback) {
if (!this.fetchCallbacks[docuri]) {
this.fetchCallbacks[docuri] = [ userCallback ]
} else {
this.fetchCallbacks[docuri].push(userCallback)
}
}
if (this.requested[docuri] === true) {
return // Don't ask again - wait for existing call
} else {
this.requested[docuri] = true
}
if (!options.noMeta && rterm && rterm.uri) {
kb.add(docterm.uri, ns.link('requestedBy'), rterm.uri, this.appNode)
}
var useJQuery = typeof jQuery !== 'undefined'
if (!useJQuery) {
var xhr = $rdf.Util.XMLHTTPFactory()
var req = xhr.req = kb.bnode()
xhr.options = options
xhr.resource = docterm
xhr.requestedURI = args[0]
} else {
var req = kb.bnode()
}
var sf = this
var now = new Date()
var timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '] '
if (!options.noMeta) {
kb.add(req, ns.rdfs('label'), kb.literal(timeNow + ' Request for ' + docuri), this.appNode)
kb.add(req, ns.link('requestedURI'), kb.literal(docuri), this.appNode)
kb.add(req, ns.link('status'), kb.collection(), this.appNode)
}
// This should not be stored in the store, but in the JS data
/*
if (typeof kb.anyStatementMatching(this.appNode, ns.link("protocol"), $rdf.uri.protocol(docuri)) === "undefined") {
// update the status before we break out
this.failFetch(xhr, "Unsupported protocol: "+$rdf.uri.protocol(docuri))
return xhr
}
*/
var checkCredentialsRetry = function () {
if (!xhr.withCredentials) return false // not dealt with
console.log('@@ Retrying with no credentials for ' + xhr.resource)
xhr.abort()
delete sf.requested[docuri] // forget the original request happened
var newopt = {}
for (var opt in options) {
if (options.hasOwnProperty(opt)) {
newopt[opt] = options[opt]
}
}
newopt.withCredentials = false
sf.addStatus(xhr.req, 'Abort: Will retry with credentials SUPPRESSED to see if that helps')
sf.requestURI(docuri, rterm, newopt, xhr.userCallback) // usercallback already registered (with where?)
return true
}
var onerrorFactory = function (xhr) {
return function (event) {
xhr.onErrorWasCalled = true // debugging and may need it
if (typeof document !== 'undefined') { // Mashup situation, not node etc
if ($rdf.Fetcher.crossSiteProxyTemplate && document.location && !xhr.proxyUsed) {
var hostpart = $rdf.uri.hostpart
var here = '' + document.location
var uri = xhr.resource.uri
if (hostpart(here) && hostpart(uri) && hostpart(here) !== hostpart(uri)) {
if (xhr.status === 401 || xhr.status === 403 || xhr.status === 404) {
onreadystatechangeFactory(xhr)()
} else {
var newURI = $rdf.Fetcher.crossSiteProxy(uri)
sf.addStatus(xhr.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>')
if (xhr.aborted) return
var kb = sf.store
var oldreq = xhr.req
if (!xhr.options.noMeta) {
kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), oldreq)
}
xhr.abort()
xhr.aborted = true
sf.addStatus(oldreq, 'redirected to new request') // why
// the callback throws an exception when called from xhr.onerror (so removed)
// sf.fireCallbacks('done', args) // Are these args right? @@@ Not done yet! done means success
sf.requested[xhr.resource.uri] = 'redirected'
if (sf.fetchCallbacks[xhr.resource.uri]) {
if (!sf.fetchCallbacks[newURI]) {
sf.fetchCallbacks[newURI] = []
}
sf.fetchCallbacks[newURI] === sf.fetchCallbacks[newURI].concat(sf.fetchCallbacks[xhr.resource.uri])
delete sf.fetchCallbacks[xhr.resource.uri]
}
var xhr2 = sf.requestURI(newURI, xhr.resource, options)
if (xhr2) {
xhr2.proxyUsed = true // only try the proxy once
}
if (xhr2 && xhr2.req) {
if (!xhr.options.noMeta) {
kb.add(xhr.req,
kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'),
xhr2.req,
sf.appNode)
}
return
}
}
}
if (checkCredentialsRetry(xhr)) {
return
}
xhr.status = 999 //
}
} // mashu
} // function of event
} // onerrorFactory
// Set up callbacks
var onreadystatechangeFactory = function (xhr) {
return function () {
var handleResponse = function () {