forked from softwaresaved/fuji
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata_harvester.py
1556 lines (1474 loc) · 81.3 KB
/
metadata_harvester.py
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
# SPDX-FileCopyrightText: 2020 PANGAEA (https://www.pangaea.de/)
#
# SPDX-License-Identifier: MIT
import enum
import hashlib
import io
import logging
import mimetypes
import re
from urllib.parse import urljoin, urlparse
import extruct
import lxml
import rdflib
from bs4 import BeautifulSoup
from pyRdfa import pyRdfa
from rapidfuzz import fuzz, process
from tldextract import extract
# from fuji_server.controllers.fair_check import ME
from fuji_server.helper.identifier_helper import IdentifierHelper
from fuji_server.helper.metadata_collector import MetaDataCollector, MetadataOfferingMethods, MetadataSources
from fuji_server.helper.metadata_collector_datacite import MetaDataCollectorDatacite
from fuji_server.helper.metadata_collector_dublincore import MetaDataCollectorDublinCore
from fuji_server.helper.metadata_collector_highwire_eprints import MetaDataCollectorHighwireEprints
from fuji_server.helper.metadata_collector_microdata import MetaDataCollectorMicroData
from fuji_server.helper.metadata_collector_opengraph import MetaDataCollectorOpenGraph
from fuji_server.helper.metadata_collector_ore_atom import MetaDataCollectorOreAtom
from fuji_server.helper.metadata_collector_rdf import MetaDataCollectorRdf
from fuji_server.helper.metadata_collector_xml import MetaDataCollectorXML
from fuji_server.helper.metadata_mapper import Mapper
from fuji_server.helper.preprocessor import Preprocessor
from fuji_server.helper.request_helper import AcceptTypes, RequestHelper
class MetadataHarvester:
LOG_SUCCESS = 25
LOG_FAILURE = 35
signposting_relation_types = [
"describedby",
"item",
"license",
"type",
"collection",
"author",
"linkset",
"cite-as",
]
def __init__(
self,
uid,
use_datacite=True,
logger=None,
auth_token=None,
auth_token_type="Basic",
allowed_harvesting_methods=None,
allowed_metadata_standards=None,
):
uid_bytes = uid.encode("utf-8")
self.test_id = hashlib.sha1(uid_bytes).hexdigest()
# str(base64.urlsafe_b64encode(uid_bytes), "utf-8") # an id we can use for caching etc
if isinstance(uid, str):
uid = uid.strip()
self.id = self.input_id = uid
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(self.test_id)
self.auth_token = auth_token
self.auth_token_type = auth_token_type
self.landing_html = None
self.landing_url = None
self.landing_origin = None
self.landing_domain = None
self.landing_page_status = None
self.landing_redirect_list = [] # urlsvisited during redirects
self.landing_redirect_status_list = [] # list with stati
self.landing_content_type = None
self.origin_url = None
self.pid_url = None
self.redirect_url = None # usually the landing page url
self.repeat_pid_check = False
self.related_resources = []
self.metadata_merged = {}
self.typed_links = []
self.STANDARD_PROTOCOLS = Preprocessor.get_standard_protocols()
# elements which need to be there
self.reference_elements = Mapper.REFERENCE_METADATA_LIST.value.copy()
self.valid_pid_types = IdentifierHelper.VALID_PIDS
self.namespace_uri = []
self.metadata_sources = []
self.metadata_unmerged = []
self.pid_scheme = None
self.linked_namespace_uri = {}
self.signposting_header_links = []
self.use_datacite = use_datacite
self.is_html_page = False
# Do something with this
self.pid_collector = {}
logging.addLevelName(self.LOG_SUCCESS, "SUCCESS")
logging.addLevelName(self.LOG_FAILURE, "FAILURE")
# set allowed methods for metadata harvesting
self.allowed_harvesting_methods = [i for i in MetaDataCollector.getEnumMethodNames()]
if allowed_harvesting_methods:
if all(isinstance(x, enum.Enum) for x in allowed_harvesting_methods):
self.allowed_harvesting_methods = allowed_harvesting_methods
self.allowed_metadata_standards = None
if allowed_metadata_standards:
if isinstance(allowed_metadata_standards, list):
self.allowed_metadata_standards = allowed_metadata_standards
self.COMMUNITY_METADATA_STANDARDS = Preprocessor.get_metadata_standards()
self.COMMUNITY_METADATA_STANDARDS_URIS = {
u.strip().strip("#/"): k for k, v in self.COMMUNITY_METADATA_STANDARDS.items() for u in v.get("urls")
}
self.COMMUNITY_METADATA_STANDARDS_NAMES = {
k: v.get("title") for k, v in self.COMMUNITY_METADATA_STANDARDS.items()
}
def is_harvesting_method_allowed(self, method):
if method in self.allowed_harvesting_methods:
return True
else:
return False
def add_metadata_source(self, source):
# print(source.value)
try:
self.metadata_sources.append((source.name, source.value.get("method")))
except Exception as e:
print("Add Metadata Source Error: ", str(e))
def merge_metadata(self, metadict, url, method, format, mimetype, schema="", namespaces=[]):
try:
offering_method = None
if not isinstance(namespaces, list):
namespaces = [namespaces]
test_uris = namespaces
if schema != "":
test_uris.append(schema)
metadata_standard = self.get_metadata_standard_by_uris(test_uris)
allow_merge = True
if self.allowed_metadata_standards:
if metadata_standard in self.allowed_metadata_standards:
allow_merge = True
else:
allow_merge = False
self.logger.warning(
"FsF-F2-01M : Harvesting of this metadata is explicitely disabled in the metric configuration-:"
+ str(metadata_standard)
)
if isinstance(metadict, dict) and allow_merge is True:
# self.metadata_sources.append((method_source, 'negotiated'))
for r in metadict.keys():
if r in self.reference_elements:
# enforce lists
if r in ["keywords", "access_level", "license", "object_type"]:
if isinstance(metadict[r], str):
if r == "keywords":
metadict[r] = metadict[r].split(",")
else:
metadict[r] = [metadict[r]]
if self.metadata_merged.get(r):
msimilarity = 0
if isinstance(self.metadata_merged[r], str) and self.metadata_merged[r] != metadict[r]:
# property value similarity
msimilarity = fuzz.token_sort_ratio(self.metadata_merged[r], str(metadict[r]))
if msimilarity <= 50:
self.logger.info(
"FsF-F2-01M : Metadata property differs from metadata previously offered in a different formats -: "
+ str(r)
+ ": "
+ str(self.metadata_merged[r])[:50]
+ " vs. "
+ str(metadict[r])[:50]
)
if isinstance(self.metadata_merged[r], list):
if isinstance(metadict[r], list):
self.metadata_merged[r].extend(metadict[r])
else:
self.metadata_merged[r].append(metadict[r])
# make list unique
unique_merged = []
for e in self.metadata_merged[r]:
if e not in unique_merged:
unique_merged.append(e)
self.metadata_merged[r] = unique_merged
# overwrite old property value in case new one is longer but similar to the old one, otherwise keep the old one
elif isinstance(self.metadata_merged[r], str) and isinstance(metadict[r], str):
if len(self.metadata_merged[r]) < len(metadict[r]):
if msimilarity > 80:
self.metadata_merged[r] = metadict[r]
else:
self.metadata_merged[r] = metadict[r]
# self.reference_elements.pop(r)
# self.reference_elements.remove(r)
if metadict.get("object_identifier"):
if not isinstance(metadict.get("object_identifier"), list):
metadict["object_identifier"] = [metadict.get("object_identifier")]
for object_identifier in metadict.get("object_identifier"):
resolves_to_landing_domain = False
pid_helper = IdentifierHelper(object_identifier, self.logger)
if (
pid_helper.identifier_url not in self.pid_collector
and pid_helper.is_persistent
and pid_helper.preferred_schema in self.valid_pid_types
):
pid_record = pid_helper.get_identifier_info(self.pid_collector)
self.pid_collector[pid_helper.identifier_url] = pid_record
resolves_to_landing_domain = self.check_if_pid_resolves_to_landing_page(
pid_helper.identifier_url
)
self.pid_collector[pid_helper.identifier_url]["verified"] = resolves_to_landing_domain
if metadict.get("related_resources"):
self.related_resources.extend(metadict.get("related_resources"))
if metadict.get("object_content_identifier"):
self.logger.info(
"FsF-F3-01M : Found data links in "
+ str(format)
+ " metadata -: "
+ str(len(metadict.get("object_content_identifier")))
)
## add: mechanism ('content negotiation', 'typed links', 'embedded')
## add: format namespace
if isinstance(method, enum.Enum):
if isinstance(method.value, dict):
offering_method = method.value.get("method").acronym()
method = method.name
mdict = {
"method": method,
"offering_method": offering_method,
"url": url,
"format": format.acronym(),
"metadata_standard": metadata_standard,
"mime": mimetype,
"schema": schema,
"metadata": metadict,
"namespaces": namespaces,
}
if mdict not in self.metadata_unmerged:
self.metadata_unmerged.append(mdict)
except Exception as e:
print("Metadata Merge Error: " + str(e), format, mimetype, schema)
def exclude_null(self, dt):
if isinstance(dt, dict):
return dict((k, self.exclude_null(v)) for k, v in dt.items() if v and self.exclude_null(v))
elif isinstance(dt, list):
try:
return list(set([self.exclude_null(v) for v in dt if v and self.exclude_null(v)]))
except Exception:
return [self.exclude_null(v) for v in dt if v and self.exclude_null(v)]
elif isinstance(dt, str):
return dt.strip()
else:
return dt
def check_if_pid_resolves_to_landing_page(self, pid_url=None):
if pid_url in self.pid_collector:
candidate_landing_url = self.pid_collector[pid_url].get("resolved_url")
if candidate_landing_url and self.landing_url:
candidate_landing_url_parts = extract(candidate_landing_url)
# print(candidate_landing_url_parts )
# landing_url_parts = extract(self.landing_url)
input_id_domain = candidate_landing_url_parts.domain + "." + candidate_landing_url_parts.suffix
# landing_domain = landing_url_parts.domain + "." + landing_url_parts.suffix
if self.landing_domain != input_id_domain:
self.logger.warning(
"FsF-F1-02D : Landing page domain resolved from PID found in metadata does not match with input URL domain -:"
+ str(self.landing_domain)
+ " <> "
+ str(input_id_domain)
)
self.logger.warning(
"FsF-F2-01M : Landing page domain resolved from PID found in metadata does not match with input URL domain -:"
+ str(self.landing_domain)
+ " <> "
+ str(input_id_domain)
)
return False
else:
self.logger.info(
"FsF-F1-02D : Verified PID found in metadata since it is resolving to user input URL domain"
)
return True
else:
return False
else:
return False
def check_pidtest_repeat(self):
if not self.repeat_pid_check:
self.repeat_pid_check = False
if self.related_resources:
for relation in self.related_resources:
try:
if relation.get("relation_type") == "isPartOf" and isinstance(
relation.get("related_resource"), str
):
parent_identifier = IdentifierHelper(relation.get("related_resource"), self.logger)
if parent_identifier.is_persistent:
self.logger.info(
"FsF-F2-01M : Found parent (isPartOf) identifier which is a PID in metadata, you may consider to assess the parent"
)
except Exception as e:
print("Relation error: ", e)
pass
if self.metadata_merged.get("object_identifier"):
if isinstance(self.metadata_merged.get("object_identifier"), list):
identifiertotest = self.metadata_merged.get("object_identifier")
else:
identifiertotest = [self.metadata_merged.get("object_identifier")]
if self.pid_scheme is None:
found_pids = {}
for pidcandidate in identifiertotest:
idhelper = IdentifierHelper(pidcandidate, self.logger)
found_id_scheme = idhelper.preferred_schema
validated = False
if self.pid_collector.get(idhelper.identifier_url):
if self.pid_collector.get(idhelper.identifier_url).get("verified"):
validated = True
else:
validated = False
if idhelper.is_persistent and validated:
found_pids[found_id_scheme] = idhelper.get_identifier_url()
if len(found_pids) >= 1 and self.repeat_pid_check is False:
# print(found_pids, next(iter(found_pids.items())))
self.logger.info(
"FsF-F2-01M : Found object identifier in metadata, repeating PID check for FsF-F1-02D"
)
self.logger.info(
"FsF-F1-02D : Found object identifier in metadata during FsF-F2-01M, therefore PID check was repeated"
)
self.repeat_pid_check = True
if "doi" in found_pids:
self.pid_url = found_pids["doi"]
self.pid_scheme = "doi"
else:
self.pid_scheme, self.pid_url = next(iter(found_pids.items()))
def set_html_typed_links(self):
try:
self.landing_html = self.landing_html.decode()
except (UnicodeDecodeError, AttributeError):
pass
if isinstance(self.landing_html, str):
if self.landing_html:
try:
dom = lxml.html.fromstring(self.landing_html.encode("utf8"))
links = dom.xpath("/*/head/link")
for link in links:
source = MetadataOfferingMethods.TYPED_LINKS
href = link.attrib.get("href")
rel = link.attrib.get("rel")
type = link.attrib.get("type")
profile = link.attrib.get("format")
type = str(type).strip()
# handle relative paths
linkparts = urlparse(href)
if linkparts.scheme == "":
href = urljoin(self.landing_url, href)
if linkparts.path.endswith(".xml"):
if type not in ["application/xml", "text/xml"] and not type.endswith("+xml"):
type += "+xml"
# signposting links
# https://www.w3.org/2001/sw/RDFCore/20031212-rdfinhtml/ recommends: link rel="meta" as well as "alternate meta"
if rel in [
"meta",
"alternate meta",
"metadata",
"collection",
"author",
"describes",
"item",
"type",
"search",
"alternate",
"describedby",
"cite-as",
"linkset",
"license",
]:
if rel in self.signposting_relation_types:
source = MetadataOfferingMethods.SIGNPOSTING
self.typed_links.append(
{"url": href, "type": type, "rel": rel, "profile": profile, "source": source}
)
except:
self.logger.info("FsF-F2-01M : Typed links identification failed -:")
else:
self.logger.info("FsF-F2-01M : Expected HTML to check for typed links but received empty string ")
def set_signposting_header_links(self, content, header):
header_link_string = header.get("Link")
if header_link_string is not None:
self.signposting_header_links = self.parse_signposting_http_link_format(header_link_string)
if self.signposting_header_links:
self.logger.info(
"FsF-F1-02D : Found signposting links in response header of landingpage -: "
+ str(len(self.signposting_header_links))
)
def set_signposting_linkset_links(self):
linksetlinks = []
linksetlink = {}
if self.get_html_typed_links("linkset"):
linksetlinks = self.get_html_typed_links("linkset")
elif self.get_signposting_header_links("linkset"):
linksetlinks = self.get_signposting_header_links("linkset")
if linksetlinks:
linksetlink = linksetlinks[0]
try:
if linksetlink.get("url"):
requestHelper = RequestHelper(linksetlink.get("url"), self.logger)
requestHelper.setAcceptType(AcceptTypes.linkset)
neg_source, linkset_data = requestHelper.content_negotiate("FsF-F1-02D")
if isinstance(linkset_data, dict):
if isinstance(linkset_data.get("linkset"), list):
validlinkset = None
for candidatelinkset in linkset_data.get("linkset"):
if isinstance(candidatelinkset, dict):
if candidatelinkset.get("anchor") in [self.pid_url, self.landing_url]:
validlinkset = candidatelinkset
break
if validlinkset:
for linktype, links in validlinkset.items():
if linktype != "anchor":
if not isinstance(links, list):
links = [links]
for link in links:
if linktype in self.signposting_relation_types:
self.typed_links.append(
{
"url": link.get("href"),
"type": link.get("type"),
"rel": linktype,
"profile": link.get("profile"),
"source": MetadataOfferingMethods.SIGNPOSTING,
}
)
self.logger.info("FsF-F2-01M : Found valid Signposting Linkset in provided JSON file")
else:
self.logger.warning(
"FsF-F2-01M : Found Signposting Linkset but none of the given anchors matches landing oage or PID"
)
else:
validlinkset = False
parsed_links = self.parse_signposting_http_link_format(linkset_data.decode())
try:
if parsed_links[0].get("anchor"):
self.logger.info("FsF-F2-01M : Found valid Signposting Linkset in provided text file")
for parsed_link in parsed_links:
if parsed_link.get("anchor") in [self.pid_url, self.landing_url]:
self.typed_links.append(parsed_link)
validlinkset = True
if not validlinkset:
self.logger.warning(
"FsF-F2-01M : Found Signposting Linkset but none of the given anchors matches landing page or PID"
)
except Exception as e:
self.logger.warning(
"FsF-F2-01M : Found Signposting Linkset but could not correctly parse the file"
)
print(e)
except Exception as e:
self.logger.warning("FsF-F2-01M : Failed to parse Signposting Linkset -: " + str(e))
def get_signposting_object_identifier(self):
# check if there is a cite-as signposting link
signposting_header_pids = self.get_signposting_header_links("cite-as")
signposting_html_pids = self.get_html_typed_links("cite-as")
signposting_pid_link_list = []
if isinstance(signposting_header_pids, list):
signposting_pid_link_list = signposting_header_pids
if isinstance(signposting_html_pids, list):
signposting_pid_link_list.extend(signposting_html_pids)
if signposting_pid_link_list:
for signposting_pid_link in signposting_pid_link_list:
signposting_pid = signposting_pid_link.get("url")
if signposting_pid:
self.logger.info(
"FsF-F1-02D : Found object identifier (cite-as) in signposting links -:" + str(signposting_pid)
)
if not signposting_pid_link.get("type"):
self.logger.warning(
"FsF-F1-02D : Found cite-as signposting links has no type attribute-:"
+ str(signposting_pid)
)
signidhelper = IdentifierHelper(signposting_pid, self.logger)
if self.metadata_merged.get("object_identifier"):
if isinstance(self.metadata_merged.get("object_identifier"), list):
self.metadata_merged["object_identifier"].append(signposting_pid)
else:
self.metadata_merged["object_identifier"] = [signposting_pid]
if (
signidhelper.identifier_url not in self.pid_collector
and signidhelper.is_persistent
and signidhelper.preferred_schema in self.valid_pid_types
):
signpid_record = signidhelper.get_identifier_info(self.pid_collector)
self.pid_collector[signidhelper.identifier_url] = signpid_record
resolves_to_landing_domain = self.check_if_pid_resolves_to_landing_page(
signidhelper.identifier_url
)
self.pid_collector[signidhelper.identifier_url]["verified"] = resolves_to_landing_domain
def get_html_typed_links(self, rel="item", allkeys=True):
# Use Typed Links in HTTP Link headers to help machines find the resources that make up a publication.
# Use links to find domains specific metadata
datalinks = []
if not isinstance(rel, list):
rel = [rel]
for typed_link in self.typed_links:
if typed_link.get("rel") in rel:
if not allkeys:
typed_link = {tlkey: typed_link[tlkey] for tlkey in ["url", "type", "source"]}
datalinks.append(typed_link)
return datalinks
def get_signposting_header_links(self, rel="item", allkeys=True):
signlinks = []
if not isinstance(rel, list):
rel = [rel]
for signposting_links in self.signposting_header_links:
if signposting_links.get("rel") in rel:
if not allkeys:
signposting_links = {slkey: signposting_links[slkey] for slkey in ["url", "type", "source"]}
signlinks.append(signposting_links)
if signlinks == []:
signlinks = None
return signlinks
def parse_signposting_http_link_format(self, signposting_link_format_text):
found_signposting_links = []
for preparsed_link in signposting_link_format_text.split(","):
found_link = None
found_type, type_match, anchor_match = None, None, None
found_rel, rel_match = None, None
found_formats, formats_match = None, None
parsed_link = preparsed_link.strip().split(";")
found_link = parsed_link[0].strip()
for link_prop in parsed_link[1:]:
link_prop = str(link_prop).strip()
if link_prop.startswith("anchor"):
anchor_match = re.search(r'anchor\s*=\s*\"?([^,;"]+)\"?', link_prop)
if link_prop.startswith("rel"):
rel_match = re.search(r'rel\s*=\s*\"?([^,;"]+)\"?', link_prop)
elif link_prop.startswith("type"):
type_match = re.search(r'type\s*=\s*\"?([^,;"]+)\"?', link_prop)
elif link_prop.startswith("formats"):
formats_match = re.search(r'formats\s*=\s*\"?([^,;"]+)\"?', link_prop)
if type_match:
found_type = type_match[1]
if rel_match:
found_rel = rel_match[1]
if formats_match:
found_formats = formats_match[1]
signposting_link_dict = {
"url": found_link[1:-1],
"type": str(found_type).strip(),
"rel": str(found_rel).strip(),
"profile": found_formats,
"source": MetadataOfferingMethods.SIGNPOSTING,
}
if anchor_match:
signposting_link_dict["anchor"] = anchor_match[1]
if signposting_link_dict.get("url") and signposting_link_dict.get("rel") in self.signposting_relation_types:
found_signposting_links.append(signposting_link_dict)
return found_signposting_links
def raise_warning_if_javascript_page(self, response_content):
# check if javascript generated content only:
try:
soup = BeautifulSoup(response_content, features="html.parser")
script_content = soup.findAll("script")
for script in soup(["script", "style", "title", "noscript"]):
script.extract()
text_content = soup.get_text(strip=True)
if (len(str(script_content)) > len(str(text_content))) and len(text_content) <= 150:
self.logger.warning(
"FsF-F1-02D : Landing page seems to be JavaScript generated, could not detect enough content"
)
self.logger.warning(
"FsF-F2-01M : Landing page seems to be JavaScript generated, could not detect enough content"
)
except Exception:
pass
def clean_html_language_tag(self, response_content):
# avoid RDFa errors
try:
langregex = r"<html\s.*lang\s*=\s*\"([^\"]+)\""
lm = re.search(langregex, response_content)
if lm:
lang = lm[1]
if not re.match(r"^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$", lang):
self.logger.warning(
"FsF-F1-02D : Trying to fix invalid language tag detected in HTML -: " + str(lang)
)
response_content = response_content.replace(lang, "en")
except Exception:
pass
return response_content
def retrieve_metadata_embedded_extruct(self):
# extract contents from the landing page using extruct, which returns a dict with
# keys 'json-ld', 'microdata', 'microformat','opengraph','rdfa'
syntaxes = ["microdata", "opengraph", "json-ld"]
extracted = {}
if self.landing_html:
try:
extruct_target = self.landing_html.encode("utf-8")
except Exception:
extruct_target = self.landing_html
pass
try:
self.logger.info(
"{} : Trying to identify EMBEDDED Microdata, OpenGraph or Schema.org -: {}".format(
"FsF-F2-01M", self.landing_url
)
)
# remove html comments which sometimes fails in extruct...
try:
extruct_target = re.sub("(<!--.*?-->)", "", extruct_target.decode("utf-8")).encode("utf-8")
except Exception:
pass
extracted = extruct.extract(extruct_target, syntaxes=syntaxes, encoding="utf-8")
except Exception as e:
extracted = {}
self.logger.warning(
"{} : Failed to parse HTML embedded Microdata, OpenGraph or Schema.org -: {}".format(
"FsF-F2-01M", self.landing_url + " " + str(e)
)
)
if isinstance(extracted, dict):
extracted = dict([(k, v) for k, v in extracted.items() if len(v) > 0])
if len(extracted) == 0:
extracted = {}
else:
print("NO LANDING HTML")
return extracted
def retrieve_metadata_embedded(self):
# ======= RETRIEVE METADATA FROM LANDING PAGE =======
response_status = None
try:
self.logger.info("FsF-F2-01M : Trying to resolve input URL -: " + str(self.id))
# check if is PID in this case complete to URL and add to pid_collector
idhelper = IdentifierHelper(self.id, self.logger)
if idhelper.is_persistent:
self.pid_scheme = idhelper.preferred_schema
self.pid_url = idhelper.identifier_url
self.pid_collector[self.pid_url] = {
"pid": self.id,
"pid_url": self.pid_url,
"scheme": self.pid_scheme,
"is_persistent": True,
}
# as a input PID it is verified even if it is not resolved
self.pid_collector[self.pid_url]["verified"] = True
input_url = idhelper.get_identifier_url()
input_urlscheme = urlparse(input_url).scheme
if input_urlscheme in self.STANDARD_PROTOCOLS:
self.origin_url = input_url
requestHelper = RequestHelper(input_url, self.logger)
requestHelper.setAuthToken(self.auth_token, self.auth_token_type)
# requestHelper.setAcceptType(AcceptTypes.html_xml) # request
requestHelper.setAcceptType(AcceptTypes.default) # request
neg_source, landingpage_html = requestHelper.content_negotiate("FsF-F1-02D", ignore_html=False)
if "html" not in str(requestHelper.content_type):
self.logger.info(
"FsF-F2-01M :Content type is "
+ str(requestHelper.content_type)
+ ", therefore skipping Embedded metadata (microdata, RDFa) tests"
)
else:
self.is_html_page = True
if requestHelper.redirect_url and requestHelper.response_status == 200:
self.isLandingPageAccessible = True
self.landing_url = requestHelper.redirect_url
if self.pid_url in self.pid_collector:
self.pid_collector[self.pid_url]["verified"] = True
self.pid_collector[self.pid_url]["resolved_url"] = self.landing_url
self.redirect_url = requestHelper.redirect_url
response_status = requestHelper.response_status
self.landing_page_status = response_status
# if requestHelper.response_content:
# self.landing_url = requestHelper.redirect_url
else:
self.logger.warning(
"FsF-F2-01M :Skipping Embedded tests, no scheme/protocol detected to be able to resolve "
+ (str(self.id))
)
except Exception as e:
self.logger.error("FsF-F2-01M : Resource inaccessible -: " + str(e))
pass
if self.landing_url:
if self.landing_url not in ["https://datacite.org/invalid.html"]:
if response_status == 200:
if "html" in requestHelper.content_type:
self.raise_warning_if_javascript_page(requestHelper.response_content)
up = urlparse(self.landing_url)
upp = extract(self.landing_url)
self.landing_origin = f"{up.scheme}://{up.netloc}"
self.landing_domain = upp.domain + "." + upp.suffix
if self.is_html_page:
self.landing_html = requestHelper.getResponseContent()
self.landing_content_type = requestHelper.content_type
self.landing_redirect_list = requestHelper.redirect_list
self.landing_redirect_status_list = requestHelper.redirect_status_list
elif response_status in [401, 402, 403]:
self.isLandingPageAccessible = False
self.logger.warning(
f"FsF-F1-02D : Resource inaccessible, identifier returned http status code -: {response_status}"
)
else:
self.isLandingPageAccessible = False
self.logger.warning(
f"FsF-F1-02D : Resource inaccessible, identifier returned http status code -: {response_status}"
)
else:
self.logger.warning(f"FsF-F1-02D : Invalid DOI, identifier resolved to -: {self.landing_url}")
self.landing_url = None
try:
if requestHelper.redirect_list:
self.landing_redirect_list = requestHelper.redirect_list
self.landing_redirect_status_list = requestHelper.redirect_status_list
except:
pass
# we have to test landin_url again, because above it may have been set to None again.. (invalid DOI)
if self.landing_url and self.is_html_page:
self.set_html_typed_links()
self.set_signposting_header_links(requestHelper.response_content, requestHelper.getResponseHeader())
self.set_signposting_linkset_links()
if self.is_harvesting_method_allowed(
MetadataOfferingMethods.HTML_EMBEDDING
) or self.is_harvesting_method_allowed(MetadataOfferingMethods.MICRODATA_RDFA):
self.logger.info("FsF-F2-01M : Starting to analyse EMBEDDED metadata at -: " + str(self.landing_url))
# test if content is html otherwise skip embedded tests
# print(self.landing_content_type)
if "html" in str(self.landing_content_type):
# ========= retrieve schema.org (embedded, or from via content-negotiation if pid provided) =========
extruct_metadata = self.retrieve_metadata_embedded_extruct()
# if extruct_metadata:
ext_meta = extruct_metadata.get("json-ld")
self.logger.info("FsF-F2-01M : Trying to retrieve schema.org JSON-LD metadata from html page")
schemaorg_collector_embedded = MetaDataCollectorRdf(
loggerinst=self.logger, json_ld_content=ext_meta, source=MetadataSources.SCHEMAORG_EMBEDDED
)
source_schemaorg, schemaorg_dict = schemaorg_collector_embedded.parse_metadata()
metaformat = schemaorg_collector_embedded.metadata_format
schemaorg_dict = self.exclude_null(schemaorg_dict)
if schemaorg_dict:
self.namespace_uri.extend(schemaorg_collector_embedded.namespaces)
self.linked_namespace_uri.update(schemaorg_collector_embedded.getLinkedNamespaces())
# self.metadata_sources.append((source_schemaorg.name, source_schemaorg.value.get('method')))
self.add_metadata_source(source_schemaorg)
if schemaorg_dict.get("related_resources"):
self.related_resources.extend(schemaorg_dict.get("related_resources"))
# add object type for future reference
self.merge_metadata(
schemaorg_dict,
self.landing_url,
source_schemaorg,
metaformat,
"application/ld+json",
"http://schema.org",
schemaorg_collector_embedded.namespaces,
)
self.logger.log(
self.LOG_SUCCESS,
"FsF-F2-01M : Found schema.org JSON-LD metadata in html page -: "
+ str(schemaorg_dict.keys()),
)
else:
self.logger.info("FsF-F2-01M : schema.org JSON-LD metadata in html page UNAVAILABLE")
# ========= retrieve dublin core embedded in html page =========
self.logger.info("FsF-F2-01M : Trying to retrieve Dublin Core metadata from html page")
dc_collector = MetaDataCollectorDublinCore(
loggerinst=self.logger, sourcemetadata=self.landing_html, mapping=Mapper.DC_MAPPING
)
source_dc, dc_dict = dc_collector.parse_metadata()
dc_dict = self.exclude_null(dc_dict)
if dc_dict:
self.namespace_uri.extend(dc_collector.namespaces)
# not_null_dc = [k for k, v in dc_dict.items() if v is not None]
# self.metadata_sources.append((source_dc, 'embedded'))
self.add_metadata_source(source_dc)
if dc_dict.get("related_resources"):
self.related_resources.extend(dc_dict.get("related_resources"))
self.merge_metadata(
dc_dict,
self.landing_url,
source_dc,
dc_collector.metadata_format,
"text/html",
"http://purl.org/dc/elements/1.1/",
dc_collector.namespaces,
)
self.logger.log(
self.LOG_SUCCESS, "FsF-F2-01M : Found DublinCore metadata -: " + str(dc_dict.keys())
)
else:
self.logger.info("FsF-F2-01M : DublinCore metadata UNAVAILABLE")
# ========= retrieve embedded rdfa and microdata metadata ========
self.logger.info("FsF-F2-01M : Trying to retrieve Microdata metadata from html page")
micro_meta = extruct_metadata.get("microdata")
microdata_collector = MetaDataCollectorMicroData(
loggerinst=self.logger, sourcemetadata=micro_meta, mapping=Mapper.MICRODATA_MAPPING
)
source_micro, micro_dict = microdata_collector.parse_metadata()
if micro_dict:
# self.metadata_sources.append((source_micro, 'embedded'))
self.add_metadata_source(source_micro)
self.namespace_uri.extend(microdata_collector.getNamespaces())
micro_dict = self.exclude_null(micro_dict)
self.merge_metadata(
micro_dict,
self.landing_url,
source_micro,
microdata_collector.metadata_format,
"text/html",
"http://www.w3.org/TR/microdata",
microdata_collector.getNamespaces(),
)
self.logger.log(
self.LOG_SUCCESS, "FsF-F2-01M : Found microdata metadata -: " + str(micro_dict.keys())
)
# ================== RDFa
self.logger.info("FsF-F2-01M : Trying to retrieve RDFa metadata from html page")
rdfasource = MetadataSources.RDFA_EMBEDDED
try:
rdfa_dict = {}
rdflib_logger = logging.getLogger("rdflib")
rdflib_logger.setLevel(logging.ERROR)
try:
rdfa_html = self.landing_html.decode("utf-8")
except Exception:
rdfa_html = self.landing_html
pass
rdfa_html = self.clean_html_language_tag(rdfa_html)
rdfabuffer = io.StringIO(rdfa_html)
# rdflib is no longer supporting RDFa: https://stackoverflow.com/questions/68500028/parsing-htmlrdfa-in-rdflib
# https://github.com/RDFLib/rdflib/discussions/1582
rdfa_graph = pyRdfa(media_type="text/html").graph_from_source(rdfabuffer)
# rdfa_graph = rdflib.Graph().parse(data=rdfa_html, format='rdfa')
# filter rdfagraph drop images
clean_rdfa_graph = rdflib.Graph()
img_triple_found = False
image_suffix = [".jpg", ".jpeg", ".png", ".tif", ".gif", ".svg", ".png"]
for s, o, p in list(rdfa_graph):
if not any(x in s for x in image_suffix):
clean_rdfa_graph.add((s, o, p))
else:
img_triple_found
if img_triple_found:
self.logger.info("FsF-F2-01M : Ignoring RDFa triples indicating image links in HTML")
rdfa_graph = clean_rdfa_graph
rdfa_collector = MetaDataCollectorRdf(
loggerinst=self.logger, target_url=self.landing_url, source=rdfasource
)
try:
rdfa_dict = rdfa_collector.get_metadata_from_graph(rdfa_graph)
except Exception as e:
print("RDFa Graph error: ", e)
if len(rdfa_dict) > 0:
# self.metadata_sources.append((rdfasource, 'embedded'))
self.add_metadata_source(rdfasource)
self.namespace_uri.extend(rdfa_collector.getNamespaces())
# rdfa_dict['object_identifier']=self.pid_url
rdfa_dict = self.exclude_null(rdfa_dict)
# print(method, url, offering_method, format, mimetype, schema)
self.merge_metadata(
rdfa_dict,
self.landing_url,
rdfasource,
rdfa_collector.metadata_format,
"application/xhtml+xml",
"http://www.w3.org/ns/rdfa#",
rdfa_collector.getNamespaces(),
)
self.logger.log(
self.LOG_SUCCESS, "FsF-F2-01M : Found RDFa metadata -: " + str(rdfa_dict.keys())
)
except Exception as e:
print("RDFa parsing error", str(e))
self.logger.info(
"FsF-F2-01M : RDFa metadata parsing exception, probably no RDFa embedded in HTML -:"
+ str(e)
)
# ========= retrieve highwire and eprints embedded in html page =========
self.logger.info("FsF-F2-01M : Trying to retrieve Highwire and eprints metadata from html page")
hw_collector = MetaDataCollectorHighwireEprints(
loggerinst=self.logger, sourcemetadata=self.landing_html
)
source_hw, hw_dict = hw_collector.parse_metadata()
hw_metaformat = hw_collector.metadata_format
hw_dict = self.exclude_null(hw_dict)
if hw_dict:
self.namespace_uri.extend(hw_collector.namespaces)
# not_null_dc = [k for k, v in dc_dict.items() if v is not None]
self.add_metadata_source(source_hw)
# self.metadata_sources.append((source_hw, 'embedded'))
if hw_dict.get("related_resources"):
self.related_resources.extend(hw_dict.get("related_resources"))
self.merge_metadata(
hw_dict,
self.landing_url,
source_hw,
hw_metaformat,
"text/html",
"highwire_eprints",
hw_collector.namespaces,
)
self.logger.log(
self.LOG_SUCCESS,
"FsF-F2-01M : Found Highwire or eprints metadata -: " + str(hw_dict.keys()),
)
else:
self.logger.info("FsF-F2-01M : Highwire or eprints metadata UNAVAILABLE")
# ======== retrieve OpenGraph metadata
self.logger.info("FsF-F2-01M : Trying to retrieve OpenGraph metadata from html page")
ext_meta = extruct_metadata.get("opengraph")
opengraph_collector = MetaDataCollectorOpenGraph(
loggerinst=self.logger, sourcemetadata=ext_meta, mapping=Mapper.OG_MAPPING
)
source_opengraph, opengraph_dict = opengraph_collector.parse_metadata()
opengraph_dict = self.exclude_null(opengraph_dict)
if opengraph_dict:
self.namespace_uri.extend(opengraph_collector.namespaces)
# self.metadata_sources.append((source_opengraph, 'embedded'))
self.add_metadata_source(source_opengraph)
self.merge_metadata(
opengraph_dict,
self.landing_url,
source_opengraph,
opengraph_collector.metadata_format,
"text/html",
"https://ogp.me/",
opengraph_collector.namespaces,
)
self.logger.log(
self.LOG_SUCCESS, "FsF-F2-01M : Found OpenGraph metadata -: " + str(opengraph_dict.keys())
)
else:
self.logger.info("FsF-F2-01M : OpenGraph metadata UNAVAILABLE")
else:
self.logger.warning(
"FsF-F2-01M : Skipped EMBEDDED metadata identification of landing page at -: "
+ str(self.landing_url)
+ " expected html content but received: "
+ str(self.landing_content_type)
)
else:
self.logger.warning(
"FsF-F2-01M :Skipping Embedded tests, since no EMBEDDED method in allowed harvesting methods: "
+ (str(self.allowed_harvesting_methods))
)
############## end of embedded metadata content harvesting
if self.is_harvesting_method_allowed(
MetadataOfferingMethods.TYPED_LINKS
) or self.is_harvesting_method_allowed(MetadataOfferingMethods.SIGNPOSTING):
# ========= retrieve signposting data links
self.logger.info("FsF-F2-01M : Trying to identify Typed Links to data items in html page")
data_sign_links = self.get_signposting_header_links("item")
if data_sign_links:
self.logger.info(