forked from mjordan/islandora_workbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workbench
executable file
·1315 lines (1127 loc) · 62.5 KB
/
workbench
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
#!/usr/bin/env python3
# Usage: ./workbench --config config.yml --check
# Usage: ./workbench --config config.yml
import os
import sys
import copy
import json
import csv
import logging
import datetime
import argparse
import collections
import subprocess
import requests_cache
from progress_bar import InitBar
from rich.progress import track
from workbench_utils import *
import workbench_fields
from WorkbenchConfig import WorkbenchConfig
def create():
"""Create new nodes via POST, and add media if there are any.
"""
message = '"Create" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
path_to_rollback_csv_file = get_rollback_csv_filepath(config)
prep_rollback_csv(config, path_to_rollback_csv_file)
logging.info("Writing rollback CSV to " + path_to_rollback_csv_file)
if config['secondary_tasks'] is not None:
if args.config not in config['secondary_tasks']:
prep_node_ids_tsv(config)
csv_path = os.path.join(config['input_dir'], config['input_csv'])
node_ids = dict()
field_definitions = get_field_definitions(config, 'node')
csv_data = get_csv_data(config)
csv_column_headers = csv_data.fieldnames
node_endpoint = config['host'] + '/node?_format=json'
if config['nodes_only'] is True:
message = '"nodes_only" option in effect. No media will be created.'
print(message)
logging.info(message)
row_count = 0
for row in csv_data:
row = clean_csv_values(row)
# Create a copy of the current item's row to pass to create_media().
row_for_media = copy.deepcopy(row)
if config['paged_content_from_directories'] is True:
# Create a copy of the current item's row to pass to the
# create_children_from_directory function.
row_as_parent = copy.deepcopy(row)
id_field = row[config['id_field']]
# Add required fields.
node = {
'type': [
{'target_id': config['content_type'],
'target_type': 'node_type'}
],
'title': [
{'value': row['title']}
],
'status': [
{'value': config['published']}
]
}
# Some optional base fields.
if 'uid' in csv_column_headers:
if len(row['uid']) > 0:
node['uid'] = [{'target_id': row['uid']}]
# Reset it to empty so it doesn't throw a key error in the code
# in the "Assemble Drupal field structures..." section below.
row['uid'] = ''
if 'created' in csv_column_headers:
if len(row['created']) > 0:
node['created'] = [{'value': row['created']}]
# Reset it to empty so it doesn't throw a key error in the code
# in the "Assemble Drupal field structures..." section below.
row['created'] = ''
if 'langcode' in csv_column_headers:
if len(row['langcode']) > 0:
node['langcode'] = [{'value': row['langcode']}]
# Reset it to empty so it doesn't throw a key error in the code
# in the "Assemble Drupal field structures..." section below.
row['langcode'] = ''
# If a node with an ID that matches the current item's 'parent_id'
# value has just been created, make the item a child of the node.
if 'parent_id' in row.keys() and row['parent_id'] in node_ids:
row['field_member_of'] = node_ids[row['parent_id']]
# For children whose parent node was created in the 'primary' job.
# The secondary task data file contains the names of the YAML config
# files registered in the primary task's 'secondary_tasks' config option.
# Therefore, only tasks whose names are registered there should populate
# their objects' 'field_member_of'.
secondary_task_data = read_node_ids_tsv(config)
if args.config in secondary_task_data:
if len(secondary_task_data) > 0:
if 'field_member_of' in row and 'parent_id' in row:
row['field_member_of'] = secondary_task_data[row['parent_id']]
# Add custom (non-required) CSV fields.
entity_fields = get_entity_fields(config, 'node', config['content_type'])
# Only add config['id_field'] to required_fields if it is not a node field.
required_fields = ['file', 'title']
if config['id_field'] not in entity_fields:
required_fields.append(config['id_field'])
custom_fields = list(set(csv_column_headers) - set(required_fields))
additional_files_entries = get_additional_files_config(config)
for custom_field in custom_fields:
# Skip processing field if empty.
if len(row[custom_field].strip()) == 0:
continue
if len(additional_files_entries) > 0:
if custom_field in additional_files_entries.keys():
continue
# This field can exist in the CSV to create parent/child
# relationships and is not a Drupal field.
if custom_field == 'parent_id':
continue
# 'langcode' is a core Drupal field, but is not considered a "base field".
if custom_field == 'langcode':
continue
# 'image_alt_text' is a reserved CSV field.
if custom_field == 'image_alt_text':
continue
# 'url_alias' is a reserved CSV field.
if custom_field == 'url_alias':
continue
# 'media_use_tid' is a reserved CSV field.
if custom_field == 'media_use_tid':
continue
# 'checksum' is a reserved CSV field.
if custom_field == 'checksum':
continue
# Execute field preprocessor scripts, if any are configured. Note that these scripts
# are applied to the entire value from the CSV field and not split field values,
# e.g., if a field is multivalued, the preprocesor must split it and then reassemble
# it back into a string before returning it. Note that preprocessor scripts work only
# on string data and not on binary data like images, etc. and only on custom fields
# (so not title).
if 'preprocessors' in config and len(config['preprocessors']) > 0:
for field, command in config['preprocessors'].items():
if field in csv_column_headers:
output, return_code = preprocess_field_data(
config['subdelimiter'], row[field], command)
if return_code == 0:
preprocessor_input = copy.deepcopy(row[field])
row[field] = output.decode().strip()
logging.info(
'Preprocess command %s executed, taking "%s" as input and returning "%s".',
command,
preprocessor_input,
output.decode().strip())
else:
message = 'Preprocess command ' + command + ' failed with return code ' + str(return_code)
logging.error(message)
sys.exit(message)
# Assemble Drupal field structures for entity reference fields from CSV data.
# Entity reference fields (taxonomy_term and node)
if field_definitions[custom_field]['field_type'] == 'entity_reference':
entity_reference_field = workbench_fields.EntityReferenceField()
node = entity_reference_field.create(config, field_definitions, node, row, custom_field)
# Typed relation fields.
elif field_definitions[custom_field]['field_type'] == 'typed_relation':
typed_relation_field = workbench_fields.TypedRelationField()
node = typed_relation_field.create(config, field_definitions, node, row, custom_field)
# Geolocation fields.
elif field_definitions[custom_field]['field_type'] == 'geolocation':
geolocation_field = workbench_fields.GeolocationField()
node = geolocation_field.create(config, field_definitions, node, row, custom_field)
# Link fields.
elif field_definitions[custom_field]['field_type'] == 'link':
link_field = workbench_fields.LinkField()
node = link_field.create(config, field_definitions, node, row, custom_field)
# Authority Link fields.
elif field_definitions[custom_field]['field_type'] == 'authority_link':
link_field = workbench_fields.AuthorityLinkField()
node = link_field.create(config, field_definitions, node, row, custom_field)
# For non-entity reference and non-typed relation fields (text, integer, boolean etc.).
else:
simple_field = workbench_fields.SimpleField()
node = simple_field.create(config, field_definitions, node, row, custom_field)
node_headers = {'Content-Type': 'application/json'}
node_endpoint = '/node?_format=json'
node_response = issue_request(config, 'POST', node_endpoint, node_headers, node, None)
if node_response.status_code == 201:
node_uri = node_response.headers['location']
returned_node = json.loads(node_response.text)
# If Pathauto URL alias creation for nodes is enabled, the location header
# returns the alias, not the /node/xxx URL, which includes the node ID. In
# this case, get the node ID from the response body.
if not re.match(r'/node/\d+$', node_uri):
node_id = returned_node['nid'][0]['value']
node_uri = config['host'] + '/node/' + str(node_id)
if config['progress_bar'] is False:
print('Node for "' + row['title'] + '" (record ' + id_field + ') created at ' + node_uri + '.')
logging.info("Node for %s (record %s) created at %s.", row['title'], id_field, node_uri)
if 'output_csv' in config.keys():
write_to_output_csv(config, id_field, node_response.text, row)
else:
message = "Node for CSV record " + id_field + " not created"
print("ERROR: " + message + '.')
logging.error(message + ', HTTP response code was ' + str(node_response.status_code) + '.')
continue
# Execute node-specific post-create scripts, if any are configured.
if 'node_post_create' in config and len(config['node_post_create']) > 0:
for command in config['node_post_create']:
post_task_output, post_task_return_code = execute_entity_post_task_script(command, args.config, node_response.status_code, node_response.text)
if post_task_return_code == 0:
logging.info("Post node create script " + command + " executed successfully.")
else:
logging.error("Post node create script " + command + " failed.")
# Map ID from CSV of newly created node to its node ID so we can use it for linking child nodes, etc.
if node_response.status_code == 201:
node_nid = node_uri.rsplit('/', 1)[-1]
node_ids[id_field] = node_nid
if config['secondary_tasks'] is not None:
if args.config not in config['secondary_tasks']:
write_to_node_ids_tsv(config, id_field, node_id)
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
write_rollback_node_id(config, node_nid, path_to_rollback_csv_file)
# If there is no media file (and we're not creating paged content), move on to the next CSV row.
if config['nodes_only'] is False and config['allow_missing_files'] is False is True and 'file' in row and len(row['file'].strip()) == 0 and config['paged_content_from_directories'] is False:
if config['progress_bar'] is False:
print('- No media for ' + node_uri + ' created since its "file" field in the CSV is empty.')
logging.warning("No media for %s created since its 'file' field in the CSV is empty.", node_uri)
continue
if node_response.status_code == 201:
allowed_media_response_codes = [201, 204]
if config['nodes_only'] is False and 'file' in row and len(row['file']) != 0:
if drupal_8 is True:
media_response_status_code = create_islandora_media(config, row['file'], 'file', node_uri, row_for_media)
else:
media_response_status_code = create_media(config, row['file'], 'file', node_nid, row_for_media)
if media_response_status_code in allowed_media_response_codes:
if config['progress_bar'] is False:
print("+ Media for " + row['file'] + " created.")
logging.info("Media for %s created.", row['file'])
else:
if config['progress_bar'] is False:
print("- ERROR: Media for " + row['file'] + " not created. See log for more information.")
logging.error("Media for %s not created (HTTP respone code %s).", row['file'], media_response_status_code)
if config['nodes_only'] is False and 'additional_files' in config:
additional_files_config = get_additional_files_config(config)
if len(additional_files_config) > 0:
for additional_file_field, additional_file_media_use_tid in additional_files_config.items():
# If there is no additional media file, move on to the next "additional_files" column.
if additional_file_field in row and len(row[additional_file_field].strip()) == 0:
if config['progress_bar'] is False:
print("- Skipping empty additional_media CSV field '{field}' for {uri}.".format(field=additional_file_field, uri=node_uri))
logging.warning("- Skipping empty additional_media CSV field '%s' for %s.", node_uri, additional_file_field)
continue
filename = row[additional_file_field].strip()
file_exists = check_file_exists(config, filename)
if file_exists is False:
if config['progress_bar'] is False:
print("- WARNING: File '{file}' from additional_media CSV field '{field}' for {uri} does not exist.".format(file=filename, field=additional_file_field, uri=node_uri))
logging.warning("File '%s' from additional_media CSV field '%s' for %s does not exist.", filename, node_uri, additional_file_field)
continue
if drupal_8 is True:
media_response_status_code = create_islandora_media(config, row[additional_file_field], additional_file_field, node_uri, row_for_media, additional_file_media_use_tid)
else:
media_response_status_code = create_media(config, row[additional_file_field], additional_file_field, node_nid, row_for_media, additional_file_media_use_tid)
if media_response_status_code in allowed_media_response_codes:
if config['progress_bar'] is False:
print("+ Media for " + row[additional_file_field] + " created.")
logging.info("Media for %s created.", row[additional_file_field])
else:
if config['progress_bar'] is False:
print("- Media for " + row[additional_file_field] + " not created. See log for more information.")
logging.error("Media for %s not created (HTTP respone code %s).", row[additional_file_field], media_response_status_code)
if config['nodes_only'] is False and 'file' in row and len(row['file']) == 0 and 'additional_files' not in config and config['paged_content_from_directories'] is False:
if config['progress_bar'] is False:
print('+ No files specified in CSV for row ' + str(id_field))
logging.info("No files specified for row %s, so no media created.", str(id_field))
if config['paged_content_from_directories'] is True:
# Console output and logging are done in the create_children_from_directory() function.
create_children_from_directory(config, row_as_parent, node_nid, row['title'])
# If 'url_alias' is in the CSV, create the alias.
if 'url_alias' in row and len(row['url_alias']) > 0:
create_url_alias(config, node_nid, row['url_alias'])
write_rollback_config(config, path_to_rollback_csv_file)
def update():
"""Update nodes via PATCH. Note that PATCHing replaces the target field,
so if we are adding an additional value to a multivalued field, we need
to include the existing value(s) in our PATCH. The field classes take
care of preserving existing values in 'append' updates.
"""
message = '"Update" (' + config['update_mode'] + ') task started using config file ' + args.config + '.'
print(message)
logging.info(message)
field_definitions = get_field_definitions(config, 'node')
csv_data = get_csv_data(config)
csv_column_headers = csv_data.fieldnames
invalid_target_ids = []
row_count = 0
for row in csv_data:
if not value_is_numeric(row['node_id']):
row['node_id'] = get_nid_from_url_alias(config, row['node_id'])
node_ping_result = ping_node(config, row['node_id'], 'GET', True)
if node_ping_result is False:
if config['progress_bar'] is False:
print("Node " + row['node_id'] + " not found or not accessible, skipping update.")
logging.warning("Node " + row['node_id'] + " not found or not accessible, skipping update.")
continue
row = clean_csv_values(row)
# Add the target_id field.
node = {
'type': [
{'target_id': config['content_type']}
]
}
node_field_values = get_node_field_values(config, row['node_id'])
# Some optional base fields.
if 'uid' in csv_column_headers:
if len(row['uid']) > 0:
node['uid'] = [{'target_id': row['uid']}]
if 'langcode' in csv_column_headers:
if len(row['langcode']) > 0:
node['langcode'] = [{'value': row['langcode']}]
if 'created' in csv_column_headers:
if len(row['created']) > 0:
node['created'] = [{'value': row['created']}]
# Add custom (non-required) fields.
required_fields = ['node_id']
custom_fields = list(set(csv_column_headers) - set(required_fields))
for custom_field in custom_fields:
node_has_all_fields = True
# If node doesn't have the field, log that fact and skip updating the field.
if custom_field not in json.loads(node_ping_result):
message = f'Node {row["node_id"]} does not have a "{custom_field}" field, skipping update.'
print(f'ERROR: ' + message)
logging.warning(message)
node_has_all_fields = False
break
# Skip updating field if CSV field is empty (other than for 'delete' update mode).
# For 'delete' update mode it doesn't matter if there's anything in the CSV field,
# but users expect to be able to supply empty values for this operation.
if len(row[custom_field].strip()) == 0:
if config['update_mode'] != 'delete':
continue
# 'url_alias' is a reserved CSV field.
if custom_field == 'url_alias':
continue
# 'image_alt_text' is a reserved CSV field.
# Issue to add alt text in update task is https://github.com/mjordan/islandora_workbench/issues/166.
if custom_field == 'image_alt_text':
continue
# 'langcode' is a core Drupal field, but is not considered a base field.
if custom_field == 'langcode':
continue
# 'created' is a base field.
if custom_field == 'created':
continue
# 'uid' is a base field.
if custom_field == 'uid':
continue
# Entity reference fields (taxonomy term and node).
if field_definitions[custom_field]['field_type'] == 'entity_reference':
entity_reference_field = workbench_fields.EntityReferenceField()
node = entity_reference_field.update(config, field_definitions, node, row, custom_field, node_field_values[custom_field])
# Typed relation fields (currently, only taxonomy term)
elif field_definitions[custom_field]['field_type'] == 'typed_relation':
typed_relation_field = workbench_fields.TypedRelationField()
node = typed_relation_field.update(config, field_definitions, node, row, custom_field, node_field_values[custom_field])
# Geolocation fields.
elif field_definitions[custom_field]['field_type'] == 'geolocation':
geolocation_field = workbench_fields.GeolocationField()
node = geolocation_field.update(config, field_definitions, node, row, custom_field, node_field_values[custom_field])
# Link fields.
elif field_definitions[custom_field]['field_type'] == 'link':
link_field = workbench_fields.LinkField()
node = link_field.update(config, field_definitions, node, row, custom_field, node_field_values[custom_field])
# Authority Link fields.
elif field_definitions[custom_field]['field_type'] == 'authority_link':
link_field = workbench_fields.AuthorityLinkField()
node = link_field.update(config, field_definitions, node, row, custom_field, node_field_values[custom_field])
# For non-entity reference and non-typed relation fields (text, etc.).
else:
simple_field = workbench_fields.SimpleField()
node = simple_field.update(config, field_definitions, node, row, custom_field, node_field_values[custom_field])
if node_has_all_fields is True:
node_endpoint = config['host'] + '/node/' + row['node_id'] + '?_format=json'
node_headers = {'Content-Type': 'application/json'}
node_response = issue_request(config, 'PATCH', node_endpoint, node_headers, node)
if node_response.status_code == 200:
if config['progress_bar'] is False:
print("Node " + config['host'] + '/node/' + row['node_id'] + " updated.")
logging.info("Node %s updated.", config['host'] + '/node/' + row['node_id'])
# Execute node-specific post-create scripts, if any are configured.
if 'node_post_update' in config and len(config['node_post_update']) > 0:
for command in config['node_post_update']:
post_task_output, post_task_return_code = execute_entity_post_task_script(command, args.config, node_response.status_code, node_response.text)
if post_task_return_code == 0:
logging.info("Post node update script " + command + " executed successfully.")
else:
logging.error("Post node update script " + command + " failed.")
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
# If 'url_alias' is in the CSV, create the alias.
if 'url_alias' in row and len(row['url_alias']) > 0:
create_url_alias(config, row['node_id'], row['url_alias'])
def delete():
"""Delete nodes.
"""
message = '"Delete" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
csv_data = get_csv_data(config)
row_count = 0
for row in csv_data:
row = clean_csv_values(row)
if not value_is_numeric(row['node_id']):
row['node_id'] = get_nid_from_url_alias(config, row['node_id'])
if not ping_node(config, row['node_id']):
if config['progress_bar'] is False:
print("Node " + row['node_id'] + " not found or not " + "accessible, skipping delete.")
logging.warning("Node " + row['node_id'] + " not found or not " + "accessible, skipping delete.")
continue
# Delete the node's media first.
if config['delete_media_with_nodes'] is True:
media_endpoint = config['host'] + '/node/' + str(row['node_id']) + '/media?_format=json'
media_response = issue_request(config, 'GET', media_endpoint)
media_response_body = json.loads(media_response.text)
media_messages = []
for media in media_response_body:
if 'mid' in media:
media_id = media['mid'][0]['value']
media_delete_status_code = remove_media_and_file(config, media_id)
if media_delete_status_code == 204:
media_messages.append("+ Media " + config['host'] + '/media/' + str(media_id) + " deleted.")
node_endpoint = config['host'] + '/node/' + str(row['node_id']) + '?_format=json'
node_response = issue_request(config, 'DELETE', node_endpoint)
if node_response.status_code == 204:
if config['progress_bar'] is False:
print("Node " +
config['host'] +
'/node/' +
str(row['node_id']) +
" deleted.")
logging.info(
"Node %s deleted.",
config['host'] +
'/node/' +
str(row['node_id']))
if config['delete_media_with_nodes'] is True and config['progress_bar'] is False:
if len(media_messages):
for media_message in media_messages:
print(media_message)
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
def add_media():
"""Add media to existing nodes.
"""
message = '"Add media" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
csv_data = get_csv_data(config)
row_count = 0
for row in csv_data:
row = clean_csv_values(row)
if not value_is_numeric(row['node_id']):
row['node_id'] = get_nid_from_url_alias(config, row['node_id'])
if not ping_node(config, row['node_id']):
print("Node " + row['node_id'] + " not found or not accessible, skipping adding media.")
continue
allowed_media_response_codes = [201, 204]
node_json_url = config['host'] + '/node/' + str(row['node_id']) + '?_format=json'
node_uri = config['host'] + '/node/' + str(row['node_id'])
node_response = issue_request(config, 'HEAD', node_json_url)
if 'media_use_tid' in row:
media_use_tid_value = row['media_use_tid']
else:
# Get media use TID from config within create_media().
media_use_tid_value = None
if node_response.status_code == 200:
if 'additional_files' not in config:
if config['allow_missing_files'] is False:
if not check_file_exists(config, row['file']):
message = 'File ' + row['file'] + ' identified in CSV "file" column in for node ID ' + row['node_id'] + ' not found.'
logging.error(message)
sys.exit('Error: ' + message)
if check_file_exists(config, row['file']):
if drupal_8 is True:
media_response_status_code = create_islandora_media(config, 'file', row['file'], node_uri, row, media_use_tid_value)
else:
media_response_status_code = create_media(config, row['file'], 'file', row['node_id'], row, media_use_tid_value)
if media_response_status_code in allowed_media_response_codes:
if config['progress_bar'] is False:
print("Media for " + row['file'] + " created and added to " + node_uri)
logging.info("Media for %s created and added to %s.", row['file'], node_uri)
else:
if config['progress_bar'] is False:
print("ERROR: Media for " + row['file'] + " not created. See log for more information.")
logging.error("Media for %s not created (HTTP respone code %s).", row['file'], media_response_status_code)
else:
message = "Warning: Media for node " + row['node_id'] + " not created since CSV column 'file' is empty."
logging.error(message)
sys.exit('Error: ' + message)
else:
if check_file_exists(config, row['file']):
if drupal_8 is True:
media_response_status_code = create_islandora_media(config, 'file', row['file'], node_uri, row, media_use_tid_value)
else:
media_response_status_code = create_media(config, row['file'], 'file', row['node_id'], row, media_use_tid_value)
if media_response_status_code in allowed_media_response_codes:
if config['progress_bar'] is False:
print("Media for " + row['file'] + " created and added to " + node_uri)
logging.info("Media for %s created and added to %s.", row['file'], node_uri)
else:
if config['progress_bar'] is False:
print("ERROR: Media for " + row['file'] + " not created. See log for more information.")
logging.error("Media for %s not created (HTTP respone code %s).", row['file'], media_response_status_code)
else:
message = "Warning: Media for node " + row['node_id'] + " not created since CSV column 'file' is empty."
logging.error(message)
sys.exit('Error: ' + message)
if 'additional_files' in config:
additional_files_config = get_additional_files_config(config)
if len(additional_files_config) > 0:
for additional_file_field, additional_file_media_use_tid in additional_files_config.items():
if config['allow_missing_files'] is False:
if not check_file_exists(config, row['file']):
message = 'File ' + row[additional_file_field] + ' identified in CSV "' + additional_file_field + '" column in for node ID ' + row['node_id'] + ' not found.'
logging.error(message)
sys.exit('Error: ' + message)
else:
if len(row[additional_file_field].strip()) == 0:
if config['progress_bar'] is False:
print("Warning: Media for " + row['node_id'] + " not created since CSV column '" + additional_file_field + "' is empty.")
logging.warning("Media for node %s not created since CSV column '" + additional_file_field + "' is empty", row['node_id'])
continue
else:
file_exists = check_file_exists(config, row[additional_file_field])
if file_exists is False:
if config['progress_bar'] is False:
print('- No media for ' + node_uri + ' created since its "' + additional_file_field + '" field in the CSV is empty.')
logging.warning("No media for %s created since its '%s' field in the CSV is empty.", node_uri, additional_file_field)
continue
if drupal_8 is True:
media_response_status_code = create_islandora_media(config, row[additional_file_field], additional_file_field, node_uri, row, additional_file_media_use_tid)
else:
media_response_status_code = create_media(config, row[additional_file_field], additional_file_field, row['node_id'], row, additional_file_media_use_tid)
if media_response_status_code in allowed_media_response_codes:
if config['progress_bar'] is False:
print("Media for " + row[additional_file_field] + " created and added to " + node_uri + ".")
logging.info("Media for %s created and added to %s.", row[additional_file_field], node_uri)
else:
if config['progress_bar'] is False:
print("ERROR: Media for " + row[additional_file_field] + " not created. See log for more information.")
logging.error("Media for %s not created (HTTP response code %s).", row[additional_file_field], media_response_status_code)
else:
if config['progress_bar'] is False:
print("ERROR: Node at " + node_uri + " does not exist or is not accessible.")
logging.error("Node at %s does not exist or is not accessible (HTTP response code %s)", node_uri, node_response.status_code)
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
def delete_media():
"""Delete media from media IDs in the input CSV.
"""
message = '"Delete media" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
csv_data = get_csv_data(config)
row_count = 0
for row in csv_data:
row = clean_csv_values(row)
if not value_is_numeric(row['media_id']):
row['media_id'] = get_mid_from_media_url_alias(config, row['node_id'])
media_delete_status_code = remove_media_and_file(config, row['media_id'])
if media_delete_status_code == 204:
if config['progress_bar'] is False:
message = "Media " + config['host'] + '/media/' + str(row['media_id']) + " and associated file deleted."
print(message)
logging.info(message)
else:
message = "Media " + config['host'] + '/media/' + str(row['media_id']) + " and associated file not deleted."
print("ERROR: " + message + " See log for more information.")
logging.error(message + " HTTP response code %s.", media_delete_status_code)
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
def delete_media_by_node():
"""Delete all media from node IDs in the input CSV.
"""
message = '"Deleting media by node" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
csv_data = get_csv_data(config)
row_count = 0
for row in csv_data:
row = clean_csv_values(row)
if not value_is_numeric(row['node_id']):
row['node_id'] = get_nid_from_url_alias(config, row['row_id'])
node_ping_result = ping_node(config, row['node_id'], 'GET', True)
if node_ping_result is False:
if config['progress_bar'] is False:
message = "Node " + row['node_id'] + " not found or not accessible, skipping deleting media."
print(message)
logging.warning(message)
continue
media_ids_from_node = get_node_media_ids(config, row['node_id'], config['delete_media_by_node_media_use_tids'])
if media_ids_from_node is not False:
if len(media_ids_from_node) > 0:
for media_id in media_ids_from_node:
media_delete_status_code = remove_media_and_file(config, media_id)
if media_delete_status_code == 204:
if config['progress_bar'] is False:
message = "Node " + row['node_id'] + "'s media " + config['host'] + '/media/' + str(media_id) + " and associated files deleted."
print(message)
logging.info(message)
else:
message = "Node " + row['node_id'] + "'s media " + config['host'] + '/media/' + str(media_id) + " and associated files not deleted."
print("ERROR: " + message + " See log for more information.")
logging.error(message + " HTTP response code %s.", media_delete_status_code)
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
def create_from_files():
"""Create new nodes from files only (no CSV), and add media. The nodes will
have a title (derived from filename), and a config-defined Islandora model,
content type, and status. Media use is derived from config as well.
"""
message = '"Create from files" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
file_dir_path = config['input_dir']
files = os.listdir(file_dir_path)
path_to_rollback_csv_file = get_rollback_csv_filepath(config)
prep_rollback_csv(config, path_to_rollback_csv_file)
logging.info("Writing rollback CSV to " + path_to_rollback_csv_file)
num_files = len(files)
file_count = 0
for file_name in files:
if file_name.startswith('rollback.') and file_name.endswith('csv'):
continue
filename_without_extension = os.path.splitext(file_name)[0]
if len(filename_without_extension) > 255:
message = 'Truncating the filename "' + filename_without_extension + '" since it exceeds Drupal\'s maximum node title length of 255 characters.'
logging.error(message)
filename_without_extension = filename_without_extension[:255]
node_json = {
'type': [
{'target_id': config['content_type'],
'target_type': 'node_type'}
],
'title': [
{'value': filename_without_extension}
],
'status': [
{'value': config['published']}
]
}
# Add field_model if that field exists in the current content type.
entity_fields = get_entity_fields(config, 'node', config['content_type'])
if 'field_model' in entity_fields:
islandora_model = set_model_from_extension(file_name, config)
node_json['field_model'] = [{'target_id': islandora_model, 'target_type': 'taxonomy_term'}]
node_headers = {
'Content-Type': 'application/json'
}
node_endpoint = '/node?_format=json'
node_response = issue_request(
config,
'POST',
node_endpoint,
node_headers,
node_json,
None)
if node_response.status_code == 201:
node_uri = node_response.headers['location']
if config['progress_bar'] is False:
print(
'Node for "' +
filename_without_extension +
'" created at ' +
node_uri +
'.')
logging.info(
'Node for "%s" created at %s.',
filename_without_extension,
node_uri)
if 'output_csv' in config.keys():
write_to_output_csv(config, '', node_response.text)
node_nid = node_uri.rsplit('/', 1)[-1]
write_rollback_node_id(config, node_nid, path_to_rollback_csv_file)
# Execute node-specific post-create scripts, if any are configured.
if 'node_post_create' in config and len(config['node_post_create']) > 0:
for command in config['node_post_create']:
post_task_output, post_task_return_code = execute_entity_post_task_script(command, args.config, node_response.status_code, node_response.text)
if post_task_return_code == 0:
logging.info("Post node create script " + command + " executed successfully.")
else:
logging.error("Post node create script " + command + " failed.")
file_path = os.path.join(config['input_dir'], file_name)
fake_csv_record = collections.OrderedDict()
fake_csv_record['title'] = filename_without_extension
fake_csv_record['file'] = file_path
media_type = set_media_type(config, file_path, 'file', fake_csv_record)
if media_type == 'image':
fake_csv_record['image_alt_text'] = filename_without_extension
if drupal_8 is True:
media_response_status_code = create_islandora_media(config, file_name, 'file', node_uri, fake_csv_record)
else:
media_response_status_code = create_media(config, file_name, 'file', node_nid, fake_csv_record)
allowed_media_response_codes = [201, 204]
if media_response_status_code in allowed_media_response_codes:
if config['progress_bar'] is False:
print("+ Media for " + filename_without_extension + " created.")
logging.info("Media for %s created.", file_path)
else:
logging.error(
'Node for "%s" not created, HTTP response code was %s.',
os.path.join(
config['input_dir'],
file_name),
node_response.status_code)
if config['progress_bar'] is True:
file_count += 1
file_position = get_percentage(file_count, num_files)
pbar(file_position)
if config['progress_bar'] is True:
pbar(100)
def export_csv():
"""Export a CSV file with values, in Islandora Workbench format,
for each node in the input CSV.
"""
message = '"Export CSV" task started using config file ' + args.config + '.'
if config['export_csv_term_mode'] == 'name':
message = message + ' The "export_csv_term_mode" configuration option is set to "name", which will slow down the export.'
print(message)
logging.info(message)
field_definitions = get_field_definitions(config, 'node')
field_labels = collections.OrderedDict()
field_names = list()
for field_name in field_definitions.keys():
field_names.append(field_name)
for field_name in ['created', 'uid', 'langcode', 'title', 'node_id', 'REMOVE THIS COLUMN (KEEP THIS ROW)']:
field_names.insert(0, field_name)
if len(config['export_csv_field_list']) > 0:
field_names = config['export_csv_field_list']
deduped_field_names = list('')
[deduped_field_names.append(x) for x in field_names if x not in deduped_field_names]
# We always include 'node_id and 'REMOVE THIS COLUMN (KEEP THIS ROW)'.
if 'node_id' not in deduped_field_names:
deduped_field_names.insert(0, 'node_id')
deduped_field_names.insert(0, 'REMOVE THIS COLUMN (KEEP THIS ROW)')
for field_name in field_definitions:
if field_name in deduped_field_names:
if field_definitions[field_name]['label'] != '':
field_labels[field_name] = field_definitions[field_name]['label']
else:
field_labels[field_name] = ''
field_labels['REMOVE THIS COLUMN (KEEP THIS ROW)'] = 'LABEL (REMOVE THIS ROW)'
if config['export_csv_file_path'] is not None:
csv_file_path = config['export_csv_file_path']
else:
csv_file_path = os.path.join(config['input_dir'], config['input_csv'] + '.csv_file_with_field_values')
if os.path.exists(csv_file_path):
os.remove(csv_file_path)
csv_file = open(csv_file_path, 'a+', encoding='utf-8')
writer = csv.DictWriter(csv_file, fieldnames=deduped_field_names, lineterminator="\n")
writer.writeheader()
writer.writerow(field_labels)
cardinality = collections.OrderedDict()
cardinality['REMOVE THIS COLUMN (KEEP THIS ROW)'] = 'NUMBER OF VALUES ALLOWED (REMOVE THIS ROW)'
cardinality['node_id'] = '1'
cardinality['uid'] = '1'
cardinality['langcode'] = '1'
cardinality['created'] = '1'
cardinality['title'] = '1'
for field_name in field_definitions:
if field_definitions[field_name]['cardinality'] == -1:
cardinality[field_name] = 'unlimited'
else:
cardinality[field_name] = field_definitions[field_name]['cardinality']
cardinality_filtered = collections.OrderedDict()
for cardinality_key in cardinality.keys():
if cardinality_key in deduped_field_names:
cardinality_filtered[cardinality_key] = cardinality[cardinality_key]
writer.writerow(cardinality_filtered)
csv_data = get_csv_data(config)
row_count = 0
for row in csv_data:
row = clean_csv_values(row)
output_row = collections.OrderedDict()
if not value_is_numeric(row['node_id']):
row['node_id'] = get_nid_from_url_alias(config, row['node_id'])
if not ping_node(config, row['node_id']):
if config['progress_bar'] is False:
print("Node " + row['node_id'] + " not found or not " + "accessible, skipping export.")
logging.warning("Node " + row['node_id'] + " not found or not " + "accessible, skipping export.")
continue
# Get node.
url = f"{config['host']}/node/{row['node_id']}?_format=json"
message = f"+ Retrieving field data for node {row['node_id']} ..."
response = issue_request(config, 'GET', url)
message = f"Retrieving node {row['node_id']} from Drupal..."
if response.status_code == 200:
body = json.loads(response.text)
if body['type'][0]['target_id'] != config['content_type']:
message = "Node " + row['node_id'] + ' has the "' + body['type'][0]['target_id'] + \
'" content type, not the content type currently configured (' + config['content_type'] + "). Skipping export."
if config['progress_bar'] is False:
print("Error: " + message)
logging.error(message)
continue
for fieldname_to_serialize in deduped_field_names:
if fieldname_to_serialize in body and fieldname_to_serialize in field_definitions:
csv_data = serialize_field_json(config, field_definitions, fieldname_to_serialize, body[fieldname_to_serialize])
output_row[fieldname_to_serialize] = csv_data
else:
message = f"Attempt to get node {row['node_id']} returned a {response.status_code} status code."
print(" Error: " + message)
logging.warning(message)
return False
output_row['node_id'] = row['node_id']
writer.writerow(output_row)
if config['progress_bar'] is True:
row_count += 1
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
else:
message = message + " adding to output CSV."
print(message)
logging.info(message)
csv_file.close()
if config['progress_bar'] is True:
pbar(100)
else:
print('CSV export saved at ' + csv_file_path + '.')
def get_data_from_view():
"""Retrieve data from a Drupal View via its REST export display.
Note: We won't be able to use the progress_bar option in this task until
https://www.drupal.org/project/drupal/issues/2982729 is resolved, since
we have no way of knowing how many items are in the View output til then.
"""
message = '"Get data from View" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
view_parameters = '&'.join(config['view_parameters']) if 'view_parameters' in config else ''
view_url = config['host'] + '/' + config['view_path'].lstrip('/') + '?page=0&' + view_parameters
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 + " HTTP status code is " + str(view_path_status_code) + ".")
sys.exit("Error: " + message + " See log for more information.")