-
Notifications
You must be signed in to change notification settings - Fork 40
/
workbench_utils.py
11424 lines (10456 loc) · 478 KB
/
workbench_utils.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
"""Utility functions for Islandora Workbench.
"""
import os
import sys
import json
from json.decoder import JSONDecodeError
import csv
import openpyxl
import time
import string
import re
import copy
import logging
import random
import uuid
import datetime
import requests
import subprocess
import hashlib
import mimetypes
import collections
import urllib.parse
from pathlib import Path
from ruamel.yaml import YAML, YAMLError
from unidecode import unidecode
from progress_bar import InitBar
import edtf_validate.valid_edtf
import shutil
import itertools
import http.client
import sqlite3
import zipfile
import requests_cache
from rich.traceback import install
install()
# Set some global variables.
yaml = YAML()
EXECUTION_START_TIME = datetime.datetime.now()
INTEGRATION_MODULE_MIN_VERSION = "1.0"
# Workaround for https://github.com/mjordan/islandora_workbench/issues/360.
http.client._MAXHEADERS = 10000
http_response_times = []
# Global lists of terms to reduce queries to Drupal.
checked_terms = list()
newly_created_terms = list()
# These are the Drupal field names on the standard types of media.
file_fields = [
"field_media_file",
"field_media_image",
"field_media_document",
"field_media_audio_file",
"field_media_video_file",
]
def set_media_type(config, filepath, file_fieldname, csv_row):
"""Using either the 'media_type' or 'media_types_override' configuration
setting, determine which media bundle type to use.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
filepath: string
The value of the CSV 'file' column.
file_fieldname: string
The name of the CSV column containing the filename (usually 'file'). None if the file
isn't in a CSV field (e.g., when config['paged_content_from_directories'] is True).
csv_row : OrderedDict
The CSV row for the current item.
Returns
-------
string
A string naming the configured media type, e.g. 'image'.
"""
if "media_type" in config:
return config["media_type"]
if config["media_type_by_media_use"] and len(config["media_type_by_media_use"]) > 0:
additional_files = get_additional_files_config(config)
media_url = additional_files.get(file_fieldname)
if file_fieldname in additional_files:
for entry in config["media_type_by_media_use"]:
for key, value in entry.items():
if key == media_url:
return value
# Determine if the incomtimg filepath matches a registered eEmbed media type.
oembed_media_type = get_oembed_url_media_type(config, filepath)
if oembed_media_type is not None:
return oembed_media_type
if file_fieldname is not None and filepath.strip().startswith("http"):
preprocessed_file_path = get_preprocessed_file_path(
config, file_fieldname, csv_row
)
filename = preprocessed_file_path.split("/")[-1]
extension = filename.split(".")[-1]
extension_with_dot = "." + extension
else:
extension_with_dot = os.path.splitext(filepath)[-1]
extension = extension_with_dot[1:]
normalized_extension = extension.lower()
media_type = "file"
for types in config["media_types"]:
for type, extensions in types.items():
if normalized_extension in extensions:
media_type = type
if "media_types_override" in config:
for override in config["media_types_override"]:
for type, extensions in override.items():
if normalized_extension in extensions:
media_type = type
# If extension isn't in one of the lists, default to 'file' bundle.
return media_type
def get_oembed_url_media_type(config, filepath):
"""Since oEmbed remote media (e.g. remove video) don't have extensions, which we
use to detect the media type of local files, we use remote URL patterns to
detect if the value of the 'file' columns is an oEmbed media.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
filepath: string
The value of the CSV 'file' column.
Returns
-------
mtype : str|None
A string naming the detected media type, e.g. 'remote_video', or None
if the filepath does not start with a configured provider URL.
"""
for oembed_provider in config["oembed_providers"]:
for mtype, provider_urls in oembed_provider.items():
for provider_url in provider_urls:
if filepath.startswith(provider_url):
return mtype
return None
def get_oembed_media_types(config):
"""Get a list of the registered oEmbed media types from config.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
media_types : list
A list with the configured allowed oEmbed media type(s), e.g. ['remote_video'].
"""
media_types = list()
for omt in config["oembed_providers"]:
keys = list(omt.keys())
media_types.append(keys[0])
return media_types
def set_model_from_extension(file_name, config):
"""Using configuration options, determine which Islandora Model value
to assign to nodes created from files. Options are either a single model
or a set of mappings from file extension to Islandora Model term ID.
Parameters
----------
file_name : str
Filename that will be checked to determine Islandora Model value(s).
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
None|str|dict
None is returned if 'task' is not set to 'create_from_files'.
str is returned if 'model' config value is set, a single model term ID is str returned.
dict is returned if 'models' config value is set, a dict with a mapping of URIs or Islandora Model term ID(s)
to file extension(s) is returned.
"""
if config["task"] != "create_from_files":
return None
if "model" in config:
return config["model"]
extension_with_dot = os.path.splitext(file_name)[1]
extension = extension_with_dot[1:]
normalized_extension = extension.lower()
for model_tids in config["models"]:
for tid, extensions in model_tids.items():
if str(tid).startswith("http"):
tid = get_term_id_from_uri(config, tid)
if normalized_extension in extensions:
return tid
# If the file's extension is not listed in the config,
# We use the term ID that contains an empty extension.
if "" in extensions:
return tid
def issue_request(config, method, path, headers=None, json="", data="", query=None):
"""Issue the HTTP request to Drupal. Note: calls to non-Drupal URLs
do not use this function.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
method : str
The HTTP method to be issued for the request, e.g. POST or GET.
path : str
Path to the API endpoint that will be used for request.
headers : dict, optional
HTTP header information to be sent with request encoded as a dict.
json : dict, optional
Data to be sent with request body as JSON format, but encoded as a dict.
data : str, optional
Data to be sent in request body.
query : dict, optional
Request parameters sent as a dict.
Returns
-------
requests.Response
"""
if config["secure_ssl_only"] is False:
requests.packages.urllib3.disable_warnings()
if not config["password"]:
message = (
'Password for Drupal user not found. Please add the "password" option to your configuration '
+ "file or provide the Drupal user's password in your ISLANDORA_WORKBENCH_PASSWORD environment variable."
)
logging.error(message)
sys.exit("Error: " + message)
if config["check"] is False:
if (
"pause" in config
and method in ["POST", "PUT", "PATCH", "DELETE"]
and value_is_numeric(config["pause"])
):
time.sleep(int(config["pause"]))
if headers is None:
headers = dict()
if query is None:
query = dict()
headers.update({"User-Agent": config["user_agent"]})
# The trailing / is stripped in config, but we do it here too, just in case.
config["host"] = config["host"].rstrip("/")
if config["host"] in path:
url = path
else:
# Since we remove the trailing / from the hostname, we need to ensure
# that there is a / separating the host from the path.
if not path.startswith("/"):
path = "/" + path
url = config["host"] + path
if config["log_request_url"] is True:
logging.info(method + " " + url)
if method == "GET":
if config["log_headers"] is True:
logging.info(headers)
response = requests.get(
url,
allow_redirects=config["allow_redirects"],
verify=config["secure_ssl_only"],
auth=(config["username"], config["password"]),
params=query,
headers=headers,
)
if method == "HEAD":
if config["log_headers"] is True:
logging.info(headers)
response = requests.head(
url,
allow_redirects=config["allow_redirects"],
verify=config["secure_ssl_only"],
auth=(config["username"], config["password"]),
headers=headers,
)
if method == "POST":
if config["log_headers"] is True:
logging.info(headers)
if config["log_json"] is True:
logging.info(json)
response = requests.post(
url,
allow_redirects=config["allow_redirects"],
stream=True,
verify=config["secure_ssl_only"],
auth=(config["username"], config["password"]),
headers=headers,
json=json,
data=data,
)
if method == "PUT":
if config["log_headers"] is True:
logging.info(headers)
if config["log_json"] is True:
logging.info(json)
response = requests.put(
url,
allow_redirects=config["allow_redirects"],
stream=True,
verify=config["secure_ssl_only"],
auth=(config["username"], config["password"]),
headers=headers,
json=json,
data=data,
)
if method == "PATCH":
if config["log_headers"] is True:
logging.info(headers)
if config["log_json"] is True:
logging.info(json)
response = requests.patch(
url,
allow_redirects=config["allow_redirects"],
stream=True,
verify=config["secure_ssl_only"],
auth=(config["username"], config["password"]),
headers=headers,
json=json,
data=data,
)
if method == "DELETE":
if config["log_headers"] is True:
logging.info(headers)
response = requests.delete(
url,
allow_redirects=config["allow_redirects"],
verify=config["secure_ssl_only"],
auth=(config["username"], config["password"]),
headers=headers,
)
if config["log_response_status_code"] is True:
logging.info(response.status_code)
if config["log_response_body"] is True:
logging.info(response.text)
response_time = response.elapsed.total_seconds()
average_response_time = calculate_response_time_trend(config, response_time)
log_response_time_value = copy.copy(config["log_response_time"])
if "adaptive_pause" in config and value_is_numeric(config["adaptive_pause"]):
# Pause defined in config['adaptive_pause'] is included in the response time,
# so we subtract it to get the "unpaused" response time.
if average_response_time is not None and (
response_time - int(config["adaptive_pause"])
) > (average_response_time * int(config["adaptive_pause_threshold"])):
message = (
"HTTP requests paused for "
+ str(config["adaptive_pause"])
+ " seconds because request in next log entry "
+ "exceeded adaptive threshold of "
+ str(config["adaptive_pause_threshold"])
+ "."
)
time.sleep(int(config["adaptive_pause"]))
logging.info(message)
# Enable response time logging if we surpass the adaptive pause threashold.
config["log_response_time"] = True
if config["log_response_time"] is True:
parsed_query_string = urllib.parse.urlparse(url).query
if len(parsed_query_string):
url_for_logging = (
urllib.parse.urlparse(url).path + "?" + parsed_query_string
)
else:
url_for_logging = urllib.parse.urlparse(url).path
if "adaptive_pause" in config and value_is_numeric(config["adaptive_pause"]):
response_time = response_time - int(config["adaptive_pause"])
response_time_trend_entry = {
"method": method,
"response": response.status_code,
"url": url_for_logging,
"response_time": response_time,
"average_response_time": average_response_time,
}
logging.info(response_time_trend_entry)
# Set this config option back to what it was before we updated in above.
config["log_response_time"] = log_response_time_value
return response
def convert_semver_to_number(version_string):
"""Convert a Semantic Version number (e.g. Drupal's) string to a number. We only need the major
and minor numbers (e.g. 9.2).
Parameters
----------
version_string: string
The version string as retrieved from Drupal.
Returns
-------
tuple
A tuple containing the major and minor Drupal core version numbers as integers.
"""
parts = version_string.split(".")
parts = parts[:2]
int_parts = [int(part) for part in parts]
version_tuple = tuple(int_parts)
return version_tuple
def get_drupal_core_version(config):
"""Get Drupal's version number.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
string|False
The Drupal core version number string (i.e., may contain -dev, etc.).
"""
url = config["host"] + "/islandora_workbench_integration/core_version"
response = issue_request(config, "GET", url)
if response.status_code == 200:
version_body = json.loads(response.text)
return version_body["core_version"]
else:
logging.warning(
"Attempt to get Drupal core version number returned a %s status code",
response.status_code,
)
return False
def check_drupal_core_version(config):
"""Used during --check to verify if the minimum required Drupal version for workbench is being used.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
None
"""
drupal_core_version = get_drupal_core_version(config)
if drupal_core_version is not False:
core_version_number = convert_semver_to_number(drupal_core_version)
else:
message = "Workbench cannot determine Drupal's version number."
logging.error(message)
sys.exit("Error: " + message)
if core_version_number < tuple([8, 6]):
message = (
"Warning: Media creation in your version of Drupal ("
+ drupal_core_version
+ ") is less reliable than in Drupal 8.6 or higher."
)
print(message)
def check_integration_module_version(config):
"""Verifies if the minimum required version of the workbench integration module is being used.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
None
"""
version = get_integration_module_version(config)
if version is False:
message = (
"Workbench cannot determine the Islandora Workbench Integration module's version number. It must be version "
+ str(INTEGRATION_MODULE_MIN_VERSION)
+ " or higher."
)
logging.error(message)
sys.exit("Error: " + message)
else:
version_number = convert_semver_to_number(version)
minimum_version_number = convert_semver_to_number(
INTEGRATION_MODULE_MIN_VERSION
)
if version_number < minimum_version_number:
message = (
"The Islandora Workbench Integration module installed on "
+ config["host"]
+ " must be"
+ " upgraded to version "
+ str(INTEGRATION_MODULE_MIN_VERSION)
+ "."
)
logging.error(message)
sys.exit("Error: " + message)
else:
logging.info(
"OK, Islandora Workbench Integration module installed on "
+ config["host"]
+ " is at version "
+ str(version)
+ "."
)
def get_integration_module_version(config):
"""Get the Islandora Workbench Integration module's version number.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
string|False
The version number string (i.e., may contain -dev, etc.) from the
Islandora Workbench Integration module.
"""
url = config["host"] + "/islandora_workbench_integration/version"
response = issue_request(config, "GET", url)
if response.status_code == 200:
version_body = json.loads(response.text)
return version_body["integration_module_version"]
else:
logging.warning(
"Attempt to get the Islandora Workbench Integration module's version number returned a %s status code",
response.status_code,
)
return False
def ping_node(config, nid_to_ping, method="HEAD", return_json=False, warn=True):
"""Ping the node to see if it exists.
Note that HEAD requests do not return a response body.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
nid_to_ping : string
Node ID/URL/alias of the node to be pinged.
method: string, optional
Either 'HEAD' or 'GET'.
return_json: boolean, optional
If True, return the entire response body to the caller.
warn: boolean, optional
If True, write a log entry.
Returns
------
boolean|str
True if method is HEAD and node was found, the response JSON response
body if method was GET. False if request returns a non-allowed status code.
"""
incoming_nid_to_ping = copy.copy(nid_to_ping)
if nid_to_ping is False:
if warn is True:
logging.warning(
"Can't perform node ping because the provided node ID was 'False'."
)
return False
if value_is_numeric(nid_to_ping) is False:
nid_to_ping = get_nid_from_url_alias(config, nid_to_ping)
url_to_ping = config["host"] + "/node/" + str(nid_to_ping) + "?_format=json"
response = issue_request(config, method.upper(), url_to_ping)
allowed_status_codes = [200, 301, 302]
if response.status_code in allowed_status_codes:
if return_json is True:
return response.text
else:
return True
else:
if warn is True:
logging.warning(
"(%s) ping on node %s (using node ID %s) returned a %s status code.",
method.upper(),
url_to_ping,
incoming_nid_to_ping,
response.status_code,
)
return False
def verify_node_exists_by_key(config, csv_row):
"""Query a View using a value from CSV (the "key") to see if the node exists.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
csv_row :
A copy of the CSV row that represents the node we are interested in.
Returns
------
str|False
The node ID if the node exists, False if the node doesn't exist, there are more than 1 node exists,
or if there was a non-200 HTTP response.
"""
endpoint_mapping = get_node_exists_verification_view_endpoint(config)
if len(csv_row[endpoint_mapping[0]]) == 0:
row_id = csv_row[config["id_field"]]
logging.warning(
f'Can\'t verify node exists for item in row "{row_id}" since it has no value in its "{endpoint_mapping[0]}" CSV column.'
)
return False
csv_value = copy.copy(csv_row[endpoint_mapping[0]])
if config["subdelimiter"] in csv_value:
csv_value_for_url = csv_value.replace(config["subdelimiter"], "%20")
else:
csv_value_for_url = csv_value
view_url = f'{config["host"]}/{endpoint_mapping[1].lstrip("/")}?{endpoint_mapping[0]}={csv_value_for_url}'
headers = {"Content-Type": "application/json"}
response = issue_request(config, "GET", view_url, headers)
if response.status_code == 200:
body = json.loads(response.text)
if len(body) == 1:
return body[0]["nid"]
elif len(body) > 1:
logging.warning(
f'Query to View "{view_url}" found more than one node ({body}). CSV "{endpoint_mapping[0]}" value was {csv_row[endpoint_mapping[0]]}. Workbench skipped this CSV row.'
)
else:
return False
else:
logging.warning(
f"Query to View {view_url} encountered a problem: HTTP status code was {response.status_code}"
)
return False
def ping_url_alias(config, url_alias):
"""Ping the URL alias to see if it exists. Return the status code.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
url_alias : str
The string with the URL alias being pinged.
Returns
-------
int
HTTP status code.
"""
url = config["host"] + url_alias + "?_format=json"
response = issue_request(config, "GET", url)
return response.status_code
def ping_vocabulary(config, vocab_id):
"""Ping the node to see if it exists.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
vocab_id : str
The string with the vocabulary ID being pinged.
Returns
-------
boolean
Returns Ture if HTTP status code returned is 200, if not False is returned.
"""
url = (
config["host"]
+ "/entity/taxonomy_vocabulary/"
+ vocab_id.strip()
+ "?_format=json"
)
response = issue_request(config, "GET", url)
if response.status_code == 200:
return True
else:
logging.warning(
"Node ping (GET) on %s returned a %s status code.",
url,
response.status_code,
)
return False
def ping_term(config, term_id):
"""Ping the term to see if it exists.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
term_id : str
The string with the term ID being pinged.
Returns
-------
boolean
Returns Ture if HTTP status code returned is 200, if not False is returned.
"""
url = config["host"] + "/taxonomy/term/" + str(term_id).strip() + "?_format=json"
response = issue_request(config, "GET", url)
if response.status_code == 200:
return True
else:
logging.warning(
"Term ping (GET) on %s returned a %s status code.",
url,
response.status_code,
)
return False
def ping_islandora(config, print_message=True):
"""Connect to Islandora in prep for subsequent HTTP requests.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
print_message : boolean, optional
If set to True, after ping successfully performed, a status message is printed for the user.
Returns
-------
None
"""
# First, test a known request that requires Administrator-level permissions.
url = config["host"] + "/islandora_workbench_integration/version"
try:
host_response = issue_request(config, "GET", url)
except requests.exceptions.Timeout as err_timeout:
message = (
"Workbench timed out trying to reach "
+ config["host"]
+ '. Please verify the "host" setting in your configuration '
+ "and check your network connection."
)
logging.error(message)
logging.error(err_timeout)
sys.exit("Error: " + message)
except requests.exceptions.ConnectionError as error_connection:
message = (
"Workbench cannot connect to "
+ config["host"]
+ '. Please verify the "host" setting in your configuration '
+ "and check your network connection."
)
logging.error(message)
logging.error(error_connection)
sys.exit("Error: " + message)
if host_response.status_code == 404:
message = (
"Workbench cannot detect whether the Islandora Workbench Integration module is "
+ "enabled on "
+ config["host"]
+ ". Please ensure it is enabled and that its version is "
+ str(INTEGRATION_MODULE_MIN_VERSION)
+ " or higher."
)
logging.error(message)
sys.exit("Error: " + message)
not_authorized = [401, 403]
if host_response.status_code in not_authorized:
message = (
"Workbench can connect to "
+ config["host"]
+ ' but the user "'
+ config["username"]
+ '" does not have sufficient permissions to continue, or the credentials are invalid.'
)
logging.error(message)
sys.exit("Error: " + message)
if config["secure_ssl_only"] is True:
message = "OK, connection to Drupal at " + config["host"] + " verified."
else:
message = (
"OK, connection to Drupal at "
+ config["host"]
+ " verified. Ignoring SSL certificates."
)
if print_message is True:
logging.info(message)
print(message)
def ping_content_type(config):
"""Ping the content_type set in the configuration to see if it exists.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
Returns
-------
int
The HTTP response code.
"""
url = f"{config['host']}/entity/entity_form_display/node.{config['content_type']}.default?_format=json"
return issue_request(config, "GET", url).status_code
def ping_view_endpoint(config, view_url):
"""Verifies that the View REST endpoint is accessible.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
view_url
The View's REST export path.
Returns
-------
int
The HTTP response code.
"""
return issue_request(config, "HEAD", view_url).status_code
def ping_entity_reference_view_endpoint(config, fieldname, handler_settings):
"""Verifies that the REST endpoint of the View is accessible. The path to this endpoint
is defined in the configuration file's 'entity_reference_view_endpoints' option.
Necessary for entity reference fields configured as "Views: Filter by an entity reference View".
Unlike Views endpoints for taxonomy entity reference fields configured using the "default"
entity reference method, the Islandora Workbench Integration module does not provide a generic
Views REST endpoint that can be used to validate values in this type of field.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
fieldname : string
The name of the Drupal field.
handler_settings : dict
The handler_settings values from the field's configuration.
# handler_settings': {'view': {'view_name': 'mj_entity_reference_test', 'display_name': 'entity_reference_1', 'arguments': []}}
Returns
-------
bool
True if the REST endpoint is accessible, False if not.
"""
endpoint_mappings = get_entity_reference_view_endpoints(config)
if len(endpoint_mappings) == 0:
logging.warning(
"The 'entity_reference_view_endpoints' option in your configuration file does not contain any field-Views endpoint mappings."
)
return False
if fieldname not in endpoint_mappings:
logging.warning(
'The field "'
+ fieldname
+ '" is not in your "entity_reference_view_endpoints" configuration option.'
)
return False
# E.g., "http://localhost:8000/issue_452_test?name=xxx&_format=json"
url = config["host"] + endpoint_mappings[fieldname] + "?name=xxx&_format=json"
response = issue_request(config, "GET", url)
if response.status_code == 200:
return True
else:
logging.warning(
"View REST export ping (GET) on %s returned a %s status code",
url,
response.status_code,
)
return False
def ping_media_bundle(config, bundle_name):
"""Ping the Media bundle/type to see if it exists. Return the status code,
a 200 if it exists or a 404 if it doesn't exist or the Media Type REST resource
is not enabled on the target Drupal.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
bundle_name : str
Media bundle/type to be pinged.
Returns
-------
int
The HTTP response code.
"""
url = config["host"] + "/entity/media_type/" + bundle_name + "?_format=json"
response = issue_request(config, "GET", url)
return response.status_code
def ping_media(config, mid, method="HEAD", return_json=False, warn=True):
"""Ping the media to see if it exists.
Note that HEAD requests do not return a response body.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
mid :
Media ID of the media to be pinged. Could be a numeric media ID or a full URL to the media.
method: string, optional
Either 'HEAD' or 'GET'.
return_json: boolean, optional
warn: boolean, optional
Returns
------
boolean|str
True if method is HEAD and node was found, the response JSON response
body if method was GET. False if request returns a non-allowed status code.
"""
if value_is_numeric(mid) is False:
mid = get_mid_from_media_url_alias(config, mid)
if config["standalone_media_url"] is True:
url = config["host"] + "/media/" + str(mid) + "?_format=json"
else:
url = config["host"] + "/media/" + str(mid) + "/edit?_format=json"
response = issue_request(config, method.upper(), url)
allowed_status_codes = [200, 301, 302]
if response.status_code in allowed_status_codes:
if return_json is True:
return response.text
else:
return True
else:
if warn is True:
logging.warning(
"Media ping (%s) on %s returned a %s status code.",
method.upper(),
url,
response.status_code,
)
return False
def extract_media_id(config: dict, media_csv_row: dict):
"""Extract the media entity's ID from the CSV row.
Parameters
----------
config : dict
The global configuration object.
media_csv_row : OrderedDict
The CSV row containing the media entity's field names and values.
Returns
-------
str|None
The media entity's ID if it could be extracted from the CSV row and is valid, otherwise None.
"""
if "media_id" not in media_csv_row: # Media ID column is missing
logging.error("Media ID column missing in CSV file.")
return None
if not media_csv_row["media_id"]: # Media ID column is present but empty
logging.error("Row with empty media_id column detected in CSV file.")
return None
# If media ID is not numeric, assume it is a media URL alias.
if not value_is_numeric(media_csv_row["media_id"]):
# Note that this function returns False if the media URL alias does not exist.
media_id = get_mid_from_media_url_alias(config, media_csv_row["media_id"])
# Media URL alias does not exist.
if media_id is False:
logging.error(
"Media URL alias %s does not exist.", media_csv_row["media_id"]
)
return None
else: