forked from mjordan/islandora_workbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkbench_utils.py
4856 lines (4307 loc) · 233 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
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 http.client
# 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()
def set_media_type(config, filepath, file_fieldname, csv_row):
"""Using configuration options, determine which media bundle type to use.
Options are either a single media type or a set of mappings from
file extenstion to media type.
"""
if 'media_type' in config:
return config['media_type']
if filepath.strip().startswith('http'):
preprocessed_file_path = get_prepocessed_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 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 'password' not in config:
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']})
config['host'] = config['host'].rstrip('/')
if config['host'] in path:
url = path
else:
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:
url_for_logging = urllib.parse.urlparse(url).path + '?' + urllib.parse.urlparse(url).query
if 'adaptive_pause' in config and value_is_numeric(config['adaptive_pause']):
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 object defined by set_config_defaults().
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 set_drupal_8(config):
"""Used for integration tests only, in which case it will either be True or False.
"""
if config['drupal_8'] is not None:
return config['drupal_8']
drupal_8 = False
drupal_core_version_string = get_drupal_core_version(config)
if drupal_core_version_string is not False:
drupal_core_version = convert_semver_to_number(drupal_core_version_string)
else:
message = "Workbench cannot determine Drupal's version number."
logging.error(message)
sys.exit('Error: ' + message)
if drupal_core_version < tuple([8, 6]):
drupal_8 = True
return drupal_8
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 object defined by set_config_defaults().
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.
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 node not found.
"""
url = config['host'] + '/node/' + str(nid) + '?_format=json'
response = issue_request(config, method.upper(), url)
# @todo: Add 301 and 302 to the allowed status codes?
if response.status_code == 200:
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_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_path(config, view_url):
return issue_request(config, 'HEAD', view_url).status_code
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 object defined by set_config_defaults().
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.
"""
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 object defined by set_config_defaults().
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 object defined by set_config_defaults().
entity_type : string
One of 'node', 'media', or 'taxonomy_term'.
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
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
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}
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']
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
field_definitions['term_name'] = {'entity_type': 'taxonomy_term', 'required': True, 'label': 'Name', 'field_type': 'string', 'cardinality': 1, 'max_length': 255, 'target_type': None}
if entity_type == 'media':
# @note: this section is incomplete.
fields = get_entity_fields(config, entity_type, bundle_type)
for fieldname in fields:
field_definitions[fieldname] = {}
if entity_type == 'media' and 'file_extensions' in field_config['settings']:
field_definitions[fieldname]['file_extensions'] = field_config['settings']['file_extensions']
if entity_type == 'media':
field_definitions[fieldname]['media_type'] = bundle_type
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)
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 object defined by set_config_defaults().
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)
def get_entity_field_storage(config, fieldname, entity_type):
"""Get a specific fields's storage configuration.
Example query for taxo terms: /entity/field_storage_config/taxonomy_term.field_external_uri?_format=json
"""
field_storage_endpoint = config['host'] + '/entity/field_storage_config/' + entity_type + '.' + fieldname + '?_format=json'
field_storage_response = issue_request(config, 'GET', field_storage_endpoint)
if field_storage_response.status_code == 200:
return field_storage_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)
def check_input(config, args):
"""Validate the config file and input data.
"""
logging.info(
'Starting configuration check for "%s" task using config file %s.',
config['task'],
args.config)
ping_islandora(config, print_message=False)
check_integration_module_version(config)
base_fields = ['title', 'status', 'promote', 'sticky', 'uid', 'created']
# Any new reserved columns introduced into the CSV need to be removed here. 'langcode' is a standard Drupal field
# but it doesn't show up in any field configs.
reserved_fields = ['file', 'media_use_tid', 'checksum', 'node_id', 'url_alias', 'image_alt_text', 'parent_id', 'langcode']
entity_fields = get_entity_fields(config, 'node', config['content_type'])
if config['id_field'] not in entity_fields:
reserved_fields.append(config['id_field'])
# Check the config file.
tasks = [
'create',
'update',
'delete',
'add_media',
'delete_media',
'delete_media_by_node',
'create_from_files',
'create_terms',
'export_csv',
'get_data_from_view'
]
joiner = ', '
if config['task'] not in tasks:
message = '"task" in your configuration file must be one of "create", "update", "delete", ' + \
'"add_media", "delete_media", "delete_media_by_node", "create_from_files", "create_terms", "export_csv", or "get_data_from_view".'
logging.error(message)
sys.exit('Error: ' + message)
config_keys = list(config.keys())
config_keys.remove('check')
# Check for presence of required config keys, which varies by task.
if config['task'] == 'create':
if config['nodes_only'] is True:
message = '"nodes_only" option in effect. Media files will not be checked/validated.'
print(message)
logging.info(message)
create_required_options = [
'task',
'host',
'username',
'password']
for create_required_option in create_required_options:
if create_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(create_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'update':
update_required_options = [
'task',
'host',
'username',
'password']
for update_required_option in update_required_options:
if update_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(update_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
update_mode_options = ['replace', 'append', 'delete']
if config['update_mode'] not in update_mode_options:
message = 'Your "update_mode" config option must be one of the following: ' + joiner.join(update_mode_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'delete':
delete_required_options = [
'task',
'host',
'username',
'password']
for delete_required_option in delete_required_options:
if delete_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(delete_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'add_media':
add_media_required_options = [
'task',
'host',
'username',
'password']
for add_media_required_option in add_media_required_options:
if add_media_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(add_media_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'delete_media':
delete_media_required_options = [
'task',
'host',
'username',
'password']
for delete_media_required_option in delete_media_required_options:
if delete_media_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(delete_media_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'delete_media_by_node':
delete_media_by_node_required_options = [
'task',
'host',
'username',
'password']
for delete_media_by_node_required_option in delete_media_by_node_required_options:
if delete_media_by_node_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(delete_media_by_node_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'export_csv':
export_csv_required_options = [
'task',
'host',
'username',
'password']
for export_csv_required_option in export_csv_required_options:
if export_csv_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(export_csv_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['export_csv_term_mode'] == 'name':
message = 'The "export_csv_term_mode" configuration option is set to "name", which will slow down the export.'
print(message)
if config['task'] == 'create_terms':
create_terms_required_options = [
'task',
'host',
'username',
'password',
'vocab_id']
for create_terms_required_option in create_terms_required_options:
if create_terms_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(create_terms_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
if config['task'] == 'get_data_from_view':
get_data_from_view_required_options = [
'task',
'host',
'username',
'password',
'view_path']
for get_data_from_view_required_option in get_data_from_view_required_options:
if get_data_from_view_required_option not in config_keys:
message = 'Please check your config file for required values: ' + joiner.join(get_data_from_view_required_options) + '.'
logging.error(message)
sys.exit('Error: ' + message)
message = 'OK, configuration file has all required values (did not check for optional values).'
print(message)
logging.info(message)
# Perform checks on get_data_from_view tasks. Since this task doesn't use input_dir, input_csv, etc.,
# we exit immediately after doing these checks.
if config['task'] == 'get_data_from_view':
# First, ping the View.
view_url = config['host'] + '/' + config['view_path'].lstrip('/')
view_path_status_code = ping_view_path(config, view_url)
if view_path_status_code != 200:
message = f"Cannot access View at {view_url}."
logging.error(message)
sys.exit("Error: " + message)
else:
message = f'View REST export at "{view_url}" is accessible.'
logging.info(message)
print("OK, " + message)
# Check to make sure the output path for the CSV file is writable.
if config['data_from_view_file_path'] is not None:
csv_file_path = config['data_from_view_file_path']
else:
csv_file_path = os.path.join(config['input_dir'], os.path.basename(args.config).split('.')[0] + '.csv_file_with_data_from_view')
csv_file_path_file = open(csv_file_path, "a")
if csv_file_path_file.writable() is False:
message = f'Path to CSV file "{csv_file_path}" is not writable.'
logging.error(message)
sys.exit("Error: " + message)
else:
message = f'CSV output file location at {csv_file_path} is writable.'
logging.info(message)
print("OK, " + message)
if os.path.exists(csv_file_path):
os.remove(csv_file_path)
# If nothing has failed by now, exit with a positive, upbeat message.
print("Configuration and input data appear to be valid.")
logging.info('Configuration checked for "%s" task using config file "%s", no problems found.', config['task'], args.config)
sys.exit()
validate_input_dir(config)
check_csv_file_exists(config, 'node_fields')
# Check column headers in CSV file.
csv_data = get_csv_data(config)
csv_column_headers = csv_data.fieldnames
# Check whether each row contains the same number of columns as there are headers.
for count, row in enumerate(csv_data, start=1):
extra_headers = False
field_count = 0
for field in row:
# 'stringtopopulateextrafields' is added by get_csv_data() if there are extra headers.
if row[field] == 'stringtopopulateextrafields':
extra_headers = True
else:
field_count += 1
if extra_headers is True:
message = "Row " + str(count) + " (ID " + row[config['id_field']] + ") of the CSV file has fewer columns " + \
"than there are headers (" + str(len(csv_column_headers)) + ")."
logging.error(message)
sys.exit('Error: ' + message)
# Note: this message is also generated in get_csv_data() since CSV Writer thows an exception if the row has
# form fields than headers.
if len(csv_column_headers) < field_count:
message = "Row " + str(count) + " (ID " + row[config['id_field']] + ") of the CSV file has more columns (" + \
str(field_count) + ") than there are headers (" + str(len(csv_column_headers)) + ")."
logging.error(message)
sys.exit('Error: ' + message)
message = "OK, all " \
+ str(count) + " rows in the CSV file have the same number of columns as there are headers (" \
+ str(len(csv_column_headers)) + ")."
print(message)
logging.info(message)
# Task-specific CSV checks.
langcode_was_present = False