forked from mjordan/islandora_workbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workbench
executable file
·3730 lines (3330 loc) · 151 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 ruamel.yaml import YAML
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)
if config["ignore_existing_parent_ids"] is True:
workbench_execution_start_time = "{:%Y-%m-%d %H:%M:%S}".format(
datetime.datetime.now()
)
# If this is a secondary task, use the primary tasks execution start time.
if os.environ.get("ISLANDORA_WORKBENCH_SECONDARY_TASKS") is not None:
if os.path.abspath(args.config) in json.loads(
os.environ["ISLANDORA_WORKBENCH_SECONDARY_TASKS"]
):
# Ensure that query_csv_id_to_node_id_map_for_parents is True.
config["query_csv_id_to_node_id_map_for_parents"] = True
workbench_execution_start_time = os.environ.get(
"ISLANDORA_WORKBENCH_PRIMARY_TASK_EXECUTION_START_TIME"
)
else:
message = "'ignore_existing_parent_ids' is set to false, parent IDs from previous Workbench sessions will be used."
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)
prepare_csv_id_to_node_id_map(config)
if config["csv_headers"] == "labels":
fieldname_map_cache_path = os.path.join(
config["temp_dir"], f"node-{config['content_type']}-labels.fieldname_map"
)
if os.path.exists(fieldname_map_cache_path):
os.remove(fieldname_map_cache_path)
if config["log_term_creation"] is False:
logging.info(
"'log_term_creation' configuration setting is False. Creation of new taxonomy terms will not be logged."
)
if config["secondary_tasks"] is not None:
if os.path.abspath(args.config) not in json.loads(
os.environ["ISLANDORA_WORKBENCH_SECONDARY_TASKS"]
):
prepare_csv_id_to_node_id_map(config)
# Register the start time of the primary task so we can access it in secondary tasks.
os.environ["ISLANDORA_WORKBENCH_PRIMARY_TASK_EXECUTION_START_TIME"] = (
"{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now())
)
node_ids = dict()
csv_path = os.path.join(config["input_dir"], config["input_csv"])
field_definitions = get_field_definitions(config, "node")
csv_data = get_csv_data(config)
csv_column_headers = csv_data.fieldnames
if (
"parent_id" in csv_column_headers
and config["query_csv_id_to_node_id_map_for_parents"] is False
):
message = "Only node IDs for parents created during this session will be used (not using the CSV ID to node ID map)."
print(message)
logging.warning(message)
if (
config["query_csv_id_to_node_id_map_for_parents"] is True
and config["ignore_duplicate_parent_ids"] is True
):
message = "Ignoring duplicate parent IDs in the CSV ID to node ID map; only the most recent entries will be used."
print(message)
logging.warning(message)
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:
if (
"node_exists_verification_view_endpoint" in config
and get_node_exists_verification_view_endpoint(config) is not False
):
candidate_node_id = verify_node_exists_by_key(config, copy.copy(row))
if candidate_node_id is not False:
message = f"Item in row {row[config['id_field']]} appears to already be in Drupal ({config['host']}/node/{candidate_node_id}), skipping it."
logging.warning(message)
print(message)
continue
# Delete expired items from request_cache before processing a row.
if config["enable_http_cache"] is True:
requests_cache.delete(expired=True)
# 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"]]
unpopulated_member_of_log_message = None
# Add required fields.
row["title"] = truncate_csv_value(
"title", row[config["id_field"]], field_definitions["title"], row["title"]
)
node = {
"type": [{"target_id": config["content_type"], "target_type": "node_type"}],
"title": [{"value": row["title"]}],
}
# Some optional node 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 "published" in csv_column_headers:
if len(row["published"]) > 0:
node["status"] = [{"value": row["published"]}]
# Reset it to empty so it doesn't throw a key error in the code
# in the "Assemble Drupal field structures..." section below.
row["published"] = ""
if "promote" in csv_column_headers:
if len(row["promote"]) > 0:
node["promote"] = [{"value": row["promote"]}]
# Reset it to empty so it doesn't throw a key error in the code
# in the "Assemble Drupal field structures..." section below.
row["promote"] = ""
# print("DEBUG field_member_of", row)
if "field_member_of" in row.keys() and (
len(row["field_member_of"]) > 0
and value_is_numeric(row["field_member_of"]) is False
):
field_member_of_value_for_message = copy.copy(row["field_member_of"])
row["field_member_of"] = get_nid_from_url_alias(
config, row["field_member_of"]
)
if row["field_member_of"] is False:
# @TODO: Use this version of the message in --check.
message = f'Node identified in "field_member_of" ({field_member_of_value_for_message}) in CSV row with ID "{id_field}" cannot be found or accessed.'
print("Warning: " + message)
logging.warning(message)
# We want to collect the node IDs of items that are parents in-session
# to accommodate users who have 'query_csv_id_to_node_id_map_for_parents: false'
# in their config files. Note: this will not work with secondary tasks, if
# you're using a secondary task you need to use the CSV ID to node ID map.
# 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"]]
# Since all nodes, both ones just created and also ones created in previous runs of
# Workbench, may have entries in the node ID map database, we always query it.
if (
config["query_csv_id_to_node_id_map_for_parents"] is True
and config["csv_id_to_node_id_map_path"] is not False
and "parent_id" in row
and row["parent_id"] is not None
):
parent_node_ids_from_id_map = []
current_parent_node_id = ""
if config["ignore_duplicate_parent_ids"] is True:
query = "select node_id from csv_id_to_node_id_map where csv_id = ? order by timestamp desc limit 1"
else:
query = "select node_id from csv_id_to_node_id_map where csv_id = ?"
parent_in_id_map_result = sqlite_manager(
config,
operation="select",
query=query,
values=(row["parent_id"],),
db_file_path=config["csv_id_to_node_id_map_path"],
)
parents_from_id_map = []
for parent_in_id_map_row in parent_in_id_map_result:
parent_node_exists = ping_node(
config, parent_in_id_map_row["node_id"], warn=False
)
if parent_node_exists is True:
parent_node_ids_from_id_map.append(parent_in_id_map_row["node_id"])
if len(parent_node_ids_from_id_map) == 1:
row["field_member_of"] = parent_node_ids_from_id_map[0]
current_parent_node_id = parent_node_ids_from_id_map[0]
if len(parent_node_ids_from_id_map) > 1:
message = f'Review your Workbench log for problems with the "parent_id" value in row with ID "{id_field}" in your input CSV data.'
unpopulated_member_of_log_message = (
f"Row ID \"{id_field}\" has a \"parent_id\" value (\"{row['parent_id']}\") that corresponds to more than one node ID in the CSV ID to node ID "
+ f"map (corresponding node IDs in the map are {', '.join(parent_node_ids_from_id_map)}). Workbench cannot reliably determine the child node's (CHILDNODEID) parent "
+ 'node ID and will not populate node CHILDNODEID\'s "field_member_of".'
)
print("Warning: " + message)
# 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(str(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
# 'directory' is a reserved CSV field.
if custom_field == "directory":
continue
# We skip CSV columns whose headers use the 'media:video:field_foo' media track convention.
if custom_field.startswith("media:"):
continue
if "preprocessors" in config and custom_field in config["preprocessors"]:
row[custom_field] = preprocess_csv(config, row, custom_field)
# Assemble Drupal field structures from CSV data. If new field types are added to
# workbench_fields.py, they need to be registered in the following if/elif/else block.
# 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
)
# Entity reference revision fields (paragraphs).
elif (
field_definitions[custom_field]["field_type"]
== "entity_reference_revisions"
):
entity_reference_revisions_field = (
workbench_fields.EntityReferenceRevisionsField()
)
node = entity_reference_revisions_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
)
# If the user has configured Workbench to not query the CSV ID to node ID map,
# use the in-session node_ids list to track and assign parent node IDs.
if config["query_csv_id_to_node_id_map_for_parents"] is False:
if "parent_id" in row and row["parent_id"] in node_ids.keys():
node["field_member_of"] = [
{
"target_id": node_ids[row["parent_id"]],
"target_type": "node_type",
}
]
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:
returned_node = json.loads(node_response.text)
node_id = returned_node["nid"][0]["value"]
node_uri = config["host"] + "/node/" + str(node_id)
node_ids[id_field] = node_id
if (
"parent_id" in row
and row["parent_id"] is not None
and config["query_csv_id_to_node_id_map_for_parents"] is True
and config["csv_id_to_node_id_map_path"] is not False
):
populate_csv_id_to_node_id_map(
config, row["parent_id"], current_parent_node_id, id_field, node_id
)
elif (
config["query_csv_id_to_node_id_map_for_parents"] is False
and config["csv_id_to_node_id_map_path"] is not False
and "parent_id" in row
and row["parent_id"] in node_ids.keys()
):
populate_csv_id_to_node_id_map(
config,
row["parent_id"],
node_ids[row["parent_id"]],
id_field,
node_id,
)
else:
populate_csv_id_to_node_id_map(config, "", "", id_field, node_id)
write_rollback_node_id(config, node_id, path_to_rollback_csv_file)
if unpopulated_member_of_log_message is not None:
unpopulated_member_of_log_message = (
unpopulated_member_of_log_message.replace(
"CHILDNODEID", str(node_id)
)
)
logging.warning(unpopulated_member_of_log_message)
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():
# We pass a copy of the row into this function because Python.
write_to_output_csv(
config, id_field, node_response.text, copy.deepcopy(row)
)
else:
message = "Node for CSV record " + id_field + " not created"
print("ERROR: " + message + ".")
logging.error(
message
+ f", HTTP response code was {node_response.status_code}, response body was {node_response.content}"
)
logging.error(
'JSON request body used in previous POST to "%s" was %s.',
node_endpoint,
node,
)
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.")
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, node_id, row["url_alias"])
write_rollback_config(config, path_to_rollback_csv_file)
# If the file named in 'file' can't be found.
if "file" in row and len(row["file"].strip()) > 0:
if (
config["nodes_only"] is False
and config["paged_content_from_directories"] is False
and check_file_exists(config, row["file"].strip()) is False
):
message = (
"No media for "
+ node_uri
+ ' created since the file named the input CSV\'s "file" column (row with ID "'
+ id_field
+ '") could not be found.'
)
if config["allow_missing_files"] is False:
logging.error(message)
sys.exit("Error: " + message)
else:
if config["progress_bar"] is False:
logging.warning(message)
continue
else:
message = (
"No media for "
+ node_uri
+ ' created since its "file" column in the input CSV (row with ID "'
+ id_field
+ '") is empty.'
)
logging.warning(message)
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"].strip()) != 0
):
media_response_status_code = create_media(
config, row["file"], "file", node_id, 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 not in row:
continue
if (
additional_file_field in row
and len(row[additional_file_field].strip()) == 0
):
if config["progress_bar"] is False:
message = (
f'Media for "additional_files" CSV column "{additional_file_field}" in row with ID "{row[config["id_field"]]}" '
+ f'(node URL "{node_uri}") not created'
)
print(
"- " + message + ". See log for more information."
)
logging.error(message + " because CSV field is empty.")
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:
message = f'Media for file "{filename}" named in field "{additional_file_field}" of CSV row with ID "{row[config["id_field"]]}" not created'
print(
"- " + message + ". See log for more information."
)
logging.error(message + " because file does not exist.")
if config["allow_missing_files"] is False:
sys.exit()
else:
continue
media_response_status_code = create_media(
config,
row[additional_file_field],
additional_file_field,
node_id,
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_id)
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)
if config["csv_headers"] == "labels":
fieldname_map_cache_path = os.path.join(
config["temp_dir"], f"node-{config['content_type']}-labels.fieldname_map"
)
if os.path.exists(fieldname_map_cache_path):
os.remove(fieldname_map_cache_path)
field_definitions = get_field_definitions(config, "node")
csv_data = get_csv_data(config)
csv_column_headers = csv_data.fieldnames
if config["log_term_creation"] is False:
logging.info(
"'log_term_creation' configuration setting is False. Creation of new taxonomy terms will not be logged."
)
row_count = 0
for row in csv_data:
# WIP on #785: print("DEBUG from within update()", row)
# Delete expired items from request_cache before processing a row.
if config["enable_http_cache"] is True:
requests_cache.delete(expired=True)
node_id_to_ping = copy.copy(row["node_id"])
if not value_is_numeric(node_id_to_ping):
node_id_to_ping = get_nid_from_url_alias(config, node_id_to_ping)
node_ping_result = ping_node(config, node_id_to_ping, "GET", True)
if node_id_to_ping is False or node_ping_result is False:
if config["progress_bar"] is False:
print(
"Node "
+ str(node_id_to_ping)
+ " not found or not accessible, skipping update."
)
logging.warning(
"Node "
+ str(node_id_to_ping)
+ " not found or not accessible, skipping update."
)
continue
# 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 node 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"]}]
if "published" in csv_column_headers:
if len(row["published"]) > 0:
node["status"] = [{"value": row["published"]}]
if "promote" in csv_column_headers:
if len(row["promote"]) > 0:
node["promote"] = [{"value": row["promote"]}]
# 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.
reserved_fields = ["published", "url_alias"]
if (
custom_field not in json.loads(node_ping_result)
and custom_field not in reserved_fields
):
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
# 'published' is a reserved CSV field.
if custom_field == "published":
continue
# 'uid' is a base field.
if custom_field == "uid":
continue
# 'promote' is a base field.
if custom_field == "promote":
continue
if "preprocessors" in config and custom_field in config["preprocessors"]:
row[custom_field] = preprocess_csv(config, row, custom_field)
if custom_field == "revision_log":
continue
# Assemble Drupal field structures from CSV data. If new field types are added to
# workbench_fields.py, they need to be registered in the following if/elif/else block.
# 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],
)
# Entity reference revisions fields (paragraphs).
elif (
field_definitions[custom_field]["field_type"]
== "entity_reference_revisions"
):
entity_reference_revisions_field = (
workbench_fields.EntityReferenceRevisionsField()
)
node = entity_reference_revisions_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:
if value_is_numeric(row["node_id"]) is False:
row["node_id"] = get_nid_from_url_alias(config, row["node_id"])
node_endpoint = (
config["host"] + "/node/" + str(row["node_id"]) + "?_format=json"
)
node_headers = {"Content-Type": "application/json"}
# Make a GET request to the content type
content_type_endpoint = f"{config['host']}/entity/node_type/{config['content_type']}?_format=json"
content_type_endpoint_response = issue_request(
config, "GET", content_type_endpoint
)
# See if revisions are enabled for the content type, if so create a new revision log message.
if content_type_endpoint_response.status_code == 200:
revisions_enabled = json.loads(content_type_endpoint_response.text)[
"new_revision"
]
if revisions_enabled:
# Add revision information to node.
revision_log_message = (
row["revision_log"]
if "revision_log" in row and row["revision_log"] != ""
else "Updated by Islandora Workbench."
)
revision_json = {"revision_log": [{"value": revision_log_message}]}
node.update(revision_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/"
+ str(row["node_id"])
+ " updated."
)
logging.info(
"Node %s updated.", config["host"] + "/node/" + str(row["node_id"])
)
else:
if config["progress_bar"] is False:
print(
"Error: Node "
+ config["host"]
+ "/node/"
+ str(row["node_id"])
+ " not updated. See log for more detail."
)
logging.error(
"Node %s not updated (server response code was '%s').",
config["host"] + "/node/" + row["node_id"],
node_response.status_code,
)
# 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:
# Delete expired items from request_cache before processing a row.
if config["enable_http_cache"] is True:
requests_cache.delete(expired=True)
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:
message = f"Node {row['node_id']} not found or not accessible, skipping delete."
print(message)
logging.warning(message)
continue
# Delete the node's media first.
if config["delete_media_with_nodes"] is True:
try:
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."
)
except Exception as e:
media_messages.append(
"- ERROR: Media "
+ config["host"]
+ "/media/"
+ str(media_id)
+ " not deleted. See log for more detail."
)