forked from mjordan/islandora_workbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workbench_utils.py
6871 lines (6102 loc) · 340 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 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
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').
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']
# 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 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
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.
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 extenstion to Islandora Model term ID.
"""
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=dict(),
json='',
data='',
query={}):
"""Issue the HTTP request to Drupal. Note: calls to non-Drupal URLs
do not use this function.
"""
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']))
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'],
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'],
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'],
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.
"""
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):
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, method='HEAD', return_json=False):
"""Ping the node to see if it exists.
Note that HEAD requests do not return a response body.
Parameters
----------
method: string
Either 'HEAD' or 'GET'.
return_json: boolean
Returns
------
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(nid) is False:
nid = get_nid_from_url_alias(config, nid)
url = config['host'] + '/node/' + str(nid) + '?_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:
logging.warning("Node ping (%s) on %s returned a %s status code.", method.upper(), url, 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.
"""
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.
"""
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 (HEAD) 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.
"""
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 (HEAD) 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.
"""
# 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):
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, hander_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 (HEAD) on %s returned a %s status code", url, response.status_code)
return False
def ping_media_bundle(config, bundle_name):
"""Ping the Media bunlde/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.
"""
url = config['host'] + '/entity/media_type/' + bundle_name + '?_format=json'
response = issue_request(config, 'GET', url)
return response.status_code
def ping_remote_file(config, url):
"""Logging, exiting, etc. happens in caller, except on requests error.
"""
sections = urllib.parse.urlparse(url)
try:
response = requests.head(url, allow_redirects=True, verify=config['secure_ssl_only'])
return response.status_code
except requests.exceptions.Timeout as err_timeout:
message = 'Workbench timed out trying to reach ' + \
sections.netloc + ' while connecting to ' + url + '. Please verify that URL 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 ' + \
sections.netloc + ' while connecting to ' + url + '. Please verify that URL and check your network connection.'
logging.error(message)
logging.error(error_connection)
sys.exit('Error: ' + message)
def get_nid_from_url_alias(config, url_alias):
"""Gets a node ID from a URL alias. This function also works
canonical URLs, e.g. http://localhost:8000/node/1648.
"""
"""
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
url_alias : string
The full URL alias (or canonical URL), including http://, etc.
Returns
-------
int
The node ID, or False if the URL cannot be found.
"""
if url_alias is False:
return False
url = url_alias + '?_format=json'
response = issue_request(config, 'GET', url)
if response.status_code != 200:
return False
else:
node = json.loads(response.text)
return node['nid'][0]['value']
def get_mid_from_media_url_alias(config, url_alias):
"""Gets a media ID from a media URL alias. This function also works
with canonical URLs, e.g. http://localhost:8000/media/1234.
"""
"""
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
url_alias : string
The full URL alias (or canonical URL), including http://, etc.
Returns
-------
int
The media ID, or False if the URL cannot be found.
"""
url = url_alias + '?_format=json'
response = issue_request(config, 'GET', url)
if response.status_code != 200:
return False
else:
node = json.loads(response.text)
return node['mid'][0]['value']
def get_node_title_from_nid(config, node_id):
"""Get node title from Drupal.
"""
node_url = config['host'] + '/node/' + node_id + '?_format=json'
node_response = issue_request(config, 'GET', node_url)
if node_response.status_code == 200:
node_dict = json.loads(node_response.text)
return node_dict['title'][0]['value']
else:
return False
def get_field_definitions(config, entity_type, bundle_type=None):
"""Get field definitions from Drupal.
Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
entity_type : string
One of 'node', 'media', 'taxonomy_term', or 'paragraph'.
bundle_type : string
None for nodes (the content type can optionally be gotten from config),
the vocabulary name, or the media type (image', 'document', 'audio',
'video', 'file', etc.).
Returns
-------
dict
A dictionary with field names as keys and values arrays containing
field config data. Config data varies slightly by entity type.
"""
ping_islandora(config, print_message=False)
field_definitions = {}
if entity_type == 'node':
bundle_type = config['content_type']
fields = get_entity_fields(config, entity_type, bundle_type)
for fieldname in fields:
field_definitions[fieldname] = {}
raw_field_config = get_entity_field_config(config, fieldname, entity_type, bundle_type)
field_config = json.loads(raw_field_config)
field_definitions[fieldname]['entity_type'] = field_config['entity_type']
field_definitions[fieldname]['required'] = field_config['required']
field_definitions[fieldname]['label'] = field_config['label']
raw_vocabularies = [x for x in field_config['dependencies']['config'] if re.match("^taxonomy.vocabulary.", x)]
if len(raw_vocabularies) > 0:
vocabularies = [x.replace("taxonomy.vocabulary.", '') for x in raw_vocabularies]
field_definitions[fieldname]['vocabularies'] = vocabularies
# Reference 'handler' could be nothing, 'default:taxonomy_term' (or some other entity type), or 'views'.
if 'handler' in field_config['settings']:
field_definitions[fieldname]['handler'] = field_config['settings']['handler']
else:
field_definitions[fieldname]['handler'] = None
if 'handler_settings' in field_config['settings']:
field_definitions[fieldname]['handler_settings'] = field_config['settings']['handler_settings']
else:
field_definitions[fieldname]['handler_settings'] = None
raw_field_storage = get_entity_field_storage(config, fieldname, entity_type)
field_storage = json.loads(raw_field_storage)
field_definitions[fieldname]['field_type'] = field_storage['type']
field_definitions[fieldname]['cardinality'] = field_storage['cardinality']
if 'max_length' in field_storage['settings']:
field_definitions[fieldname]['max_length'] = field_storage['settings']['max_length']
else:
field_definitions[fieldname]['max_length'] = None
if 'target_type' in field_storage['settings']:
field_definitions[fieldname]['target_type'] = field_storage['settings']['target_type']
else:
field_definitions[fieldname]['target_type'] = None
if field_storage['type'] == 'typed_relation' and 'rel_types' in field_config['settings']:
field_definitions[fieldname]['typed_relations'] = field_config['settings']['rel_types']
if 'authority_sources' in field_config['settings']:
field_definitions[fieldname]['authority_sources'] = list(field_config['settings']['authority_sources'].keys())
else:
field_definitions[fieldname]['authority_sources'] = None
if 'allowed_values' in field_storage['settings']:
field_definitions[fieldname]['allowed_values'] = list(field_storage['settings']['allowed_values'].keys())
else:
field_definitions[fieldname]['allowed_values'] = None
# title's configuration is not returned by Drupal so we construct it here. Note: if you add a new key to
# 'field_definitions', also add it to title's entry here. Also add it for 'title' in the other entity types, below.
field_definitions['title'] = {
'entity_type': 'node',
'required': True,
'label': 'Title',
'field_type': 'string',
'cardinality': 1,
'max_length': config['max_node_title_length'],
'target_type': None,
'handler': None,
'handler_settings': None
}
if entity_type == 'taxonomy_term':
fields = get_entity_fields(config, 'taxonomy_term', bundle_type)
for fieldname in fields:
field_definitions[fieldname] = {}
raw_field_config = get_entity_field_config(config, fieldname, entity_type, bundle_type)
field_config = json.loads(raw_field_config)
field_definitions[fieldname]['entity_type'] = field_config['entity_type']
field_definitions[fieldname]['required'] = field_config['required']
field_definitions[fieldname]['label'] = field_config['label']
# Reference 'handler' could be nothing, 'default:taxonomy_term' (or some other entity type), or 'views'.
if 'handler' in field_config['settings']:
field_definitions[fieldname]['handler'] = field_config['settings']['handler']
else:
field_definitions[fieldname]['handler'] = None
if 'handler_settings' in field_config['settings']:
field_definitions[fieldname]['handler_settings'] = field_config['settings']['handler_settings']
else:
field_definitions[fieldname]['handler_settings'] = None
raw_field_storage = get_entity_field_storage(config, fieldname, entity_type)
field_storage = json.loads(raw_field_storage)
field_definitions[fieldname]['field_type'] = field_storage['type']
field_definitions[fieldname]['cardinality'] = field_storage['cardinality']
if 'max_length' in field_storage['settings']:
field_definitions[fieldname]['max_length'] = field_storage['settings']['max_length']
else:
field_definitions[fieldname]['max_length'] = None
if 'target_type' in field_storage['settings']:
field_definitions[fieldname]['target_type'] = field_storage['settings']['target_type']
else:
field_definitions[fieldname]['target_type'] = None
if 'authority_sources' in field_config['settings']:
field_definitions[fieldname]['authority_sources'] = list(field_config['settings']['authority_sources'].keys())
else:
field_definitions[fieldname]['authority_sources'] = None
if 'allowed_values' in field_storage['settings']:
field_definitions[fieldname]['allowed_values'] = list(field_storage['settings']['allowed_values'].keys())
else:
field_definitions[fieldname]['allowed_values'] = None
field_definitions['term_name'] = {
'entity_type': 'taxonomy_term',
'required': True,
'label': 'Name',
'field_type': 'string',
'cardinality': 1,
'max_length': 255,
'target_type': None,
'handler': None,
'handler_settings': None
}
if entity_type == 'media':
fields = get_entity_fields(config, entity_type, bundle_type)
for fieldname in fields:
field_definitions[fieldname] = {}
raw_field_config = get_entity_field_config(config, fieldname, entity_type, bundle_type)
field_config = json.loads(raw_field_config)
field_definitions[fieldname]['media_type'] = bundle_type
field_definitions[fieldname]['field_type'] = field_config['field_type']
if 'file_extensions' in field_config['settings']:
field_definitions[fieldname]['file_extensions'] = field_config['settings']['file_extensions']
raw_field_storage = get_entity_field_storage(config, fieldname, entity_type)
field_storage = json.loads(raw_field_storage)
field_definitions[fieldname]['field_type'] = field_storage['type']
field_definitions[fieldname]['cardinality'] = field_storage['cardinality']
if 'max_length' in field_storage['settings']:
field_definitions[fieldname]['max_length'] = field_storage['settings']['max_length']
else:
field_definitions[fieldname]['max_length'] = None
if 'target_type' in field_storage['settings']:
field_definitions[fieldname]['target_type'] = field_storage['settings']['target_type']
else:
field_definitions[fieldname]['target_type'] = None
if 'authority_sources' in field_config['settings']:
field_definitions[fieldname]['authority_sources'] = list(field_config['settings']['authority_sources'].keys())
else:
field_definitions[fieldname]['authority_sources'] = None
if 'allowed_values' in field_storage['settings']:
field_definitions[fieldname]['allowed_values'] = list(field_storage['settings']['allowed_values'].keys())
else:
field_definitions[fieldname]['allowed_values'] = None
field_definitions['name'] = {
'entity_type': 'media',
'required': True,
'label': 'Name',
'field_type': 'string',
'cardinality': 1,
'max_length': 255,
'target_type': None,
'handler': None,
'handler_settings': None
}
if entity_type == 'paragraph':
fields = get_entity_fields(config, entity_type, bundle_type)
for fieldname in fields:
# NOTE, WIP on #292. Code below copied from 'node' section above, may need modification.
field_definitions[fieldname] = {}
raw_field_config = get_entity_field_config(config, fieldname, entity_type, bundle_type)
field_config = json.loads(raw_field_config)
field_definitions[fieldname]['entity_type'] = field_config['entity_type']
field_definitions[fieldname]['required'] = field_config['required']
field_definitions[fieldname]['label'] = field_config['label']
raw_vocabularies = [x for x in field_config['dependencies']['config'] if re.match("^taxonomy.vocabulary.", x)]
if len(raw_vocabularies) > 0:
vocabularies = [x.replace("taxonomy.vocabulary.", '') for x in raw_vocabularies]
field_definitions[fieldname]['vocabularies'] = vocabularies
# Reference 'handler' could be nothing, 'default:taxonomy_term' (or some other entity type), or 'views'.
if 'handler' in field_config['settings']:
field_definitions[fieldname]['handler'] = field_config['settings']['handler']
else:
field_definitions[fieldname]['handler'] = None
if 'handler_settings' in field_config['settings']:
field_definitions[fieldname]['handler_settings'] = field_config['settings']['handler_settings']
else:
field_definitions[fieldname]['handler_settings'] = None
raw_field_storage = get_entity_field_storage(config, fieldname, entity_type)
field_storage = json.loads(raw_field_storage)
field_definitions[fieldname]['field_type'] = field_storage['type']
field_definitions[fieldname]['cardinality'] = field_storage['cardinality']
if 'max_length' in field_storage['settings']:
field_definitions[fieldname]['max_length'] = field_storage['settings']['max_length']
else:
field_definitions[fieldname]['max_length'] = None
if 'target_type' in field_storage['settings']:
field_definitions[fieldname]['target_type'] = field_storage['settings']['target_type']
else:
field_definitions[fieldname]['target_type'] = None
if field_storage['type'] == 'typed_relation' and 'rel_types' in field_config['settings']:
field_definitions[fieldname]['typed_relations'] = field_config['settings']['rel_types']
if 'authority_sources' in field_config['settings']:
field_definitions[fieldname]['authority_sources'] = list(field_config['settings']['authority_sources'].keys())
else:
field_definitions[fieldname]['authority_sources'] = None
if 'allowed_values' in field_storage['settings']:
field_definitions[fieldname]['allowed_values'] = list(field_storage['settings']['allowed_values'].keys())
else:
field_definitions[fieldname]['allowed_values'] = None
return field_definitions
def get_entity_fields(config, entity_type, bundle_type):
"""Get all the fields configured on a bundle.
"""
if ping_content_type(config) == 404:
message = f"Content type '{config['content_type']}' does not exist on {config['host']}."
logging.error(message)
sys.exit('Error: ' + message)
fields_endpoint = config['host'] + '/entity/entity_form_display/' + entity_type + '.' + bundle_type + '.default?_format=json'
bundle_type_response = issue_request(config, 'GET', fields_endpoint)
# If a vocabulary has no custom fields (like the default "Tags" vocab), this query will
# return a 404 response. So, we need to use an alternative way to check if the vocabulary
# really doesn't exist.
if bundle_type_response.status_code == 404 and entity_type == 'taxonomy_term':
fallback_fields_endpoint = '/entity/taxonomy_vocabulary/' + bundle_type + '?_format=json'
fallback_bundle_type_response = issue_request(config, 'GET', fallback_fields_endpoint)
# If this request confirms the vocabulary exists, its OK to make some assumptions
# about what fields it has.
if fallback_bundle_type_response.status_code == 200:
return []
fields = []
if bundle_type_response.status_code == 200:
node_config_raw = json.loads(bundle_type_response.text)
fieldname_prefix = 'field.field.' + entity_type + '.' + bundle_type + '.'
fieldnames = [
field_dependency.replace(
fieldname_prefix,
'') for field_dependency in node_config_raw['dependencies']['config']]
for fieldname in node_config_raw['dependencies']['config']:
fieldname_prefix = 'field.field.' + entity_type + '.' + bundle_type + '.'
if re.match(fieldname_prefix, fieldname):
fieldname = fieldname.replace(fieldname_prefix, '')
fields.append(fieldname)
else:
message = 'Workbench cannot retrieve field definitions from Drupal. Please confirm that the Field, Field Storage, and Entity Form Display REST resources are enabled.'
logging.error(message + " HTTP response code was " + str(bundle_type_response.status_code) + '.')
sys.exit('Error: ' + message)
return fields
def get_required_bundle_fields(config, entity_type, bundle_type):
"""Gets a list of required fields for the given bundle type.
"""
"""Parameters
----------
config : dict
The configuration settings defined by workbench_config.get_config().
entity_type : string
One of 'node', 'media', or 'taxonomy_term'.
bundle_type : string
The (node) content type, the vocabulary name, or the media type ('image',
'document', 'audio', 'video', 'file', etc.).
Returns
-------
list
A list of Drupal field names that are configured as required for this bundle.
"""
field_definitions = get_field_definitions(config, entity_type, bundle_type)
required_drupal_fields = list()
for drupal_fieldname in field_definitions:
if 'entity_type' in field_definitions[drupal_fieldname] and field_definitions[drupal_fieldname]['entity_type'] == entity_type:
if 'required' in field_definitions[drupal_fieldname] and field_definitions[drupal_fieldname]['required'] is True:
required_drupal_fields.append(drupal_fieldname)
return required_drupal_fields
def get_entity_field_config(config, fieldname, entity_type, bundle_type):
"""Get a specific fields's configuration.
Example query for taxo terms: /entity/field_config/taxonomy_term.islandora_media_use.field_external_uri?_format=json
"""
field_config_endpoint = config['host'] + '/entity/field_config/' + entity_type + '.' + bundle_type + '.' + fieldname + '?_format=json'
field_config_response = issue_request(config, 'GET', field_config_endpoint)
if field_config_response.status_code == 200:
return field_config_response.text
else:
message = 'Workbench cannot retrieve field definitions from Drupal. Please confirm that the Field, Field Storage, and Entity Form Display REST resources are enabled.'
logging.error(message)
sys.exit('Error: ' + message)