This repository has been archived by the owner on Jun 30, 2023. It is now read-only.
forked from mjordan/islandora_workbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkbench
executable file
·1955 lines (1664 loc) · 98 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 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)
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)
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
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:
# 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. 'status' ("published") can be overridden in CSV, below.
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 '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'] = ''
# 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 'parent_id' in row:
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:
parents_from_id_map.append(parent_in_id_map_row['node_id'])
if len(parents_from_id_map) == 1:
row['field_member_of'] = parents_from_id_map[0]
if len(parents_from_id_map) > 1:
message = 'Query of ID map for parent ID "%s" returned multiple node IDs: %s. Skpping populatiuon of field_member_of.', row['parent_id'], ', '.join(parents_from_id_map)
logging.warning(message)
print('Warning: ' + message)
continue
# 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
# We skip CSV columns whose headers use the 'media:video:field_foo' media track convention.
if custom_field.startswith('media:'):
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 re.match(r'/node/\d+$', node_uri):
node_id = node_uri.rsplit('/', 1)[-1]
else:
node_id = returned_node['nid'][0]['value']
node_uri = config['host'] + '/node/' + str(node_id)
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 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 + 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 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:
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 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("- Media for file '{file}' named in field '{field}' of CSV row '{id}' not created. " +
"See log for more information.".format(file=filename, field=additional_file_field, id=row[config['id_field']]))
logging.warning('File "%s" from additional_file field "%s" for CSV row "%s" does not exist, cannot create media.', filename, additional_file_field, row[config['id_field']])
continue
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)
# 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)
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
invalid_target_ids = []
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:
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
# 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']}]
if 'published' in csv_column_headers:
if len(row['published']) > 0:
node['status'] = [{'value': row['published']}]
# 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
# 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:
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:
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:
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']):
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']):
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
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 update_media() -> None:
""" Update media from media IDs in the input CSV. """
from typing import Optional
# ========================================================= Helper functions =========================================================
def get_media_type(media_id: str, get_media_response: requests.Response) -> Optional[str]:
"""Get the media type of a media entity.
Parameters:
- media_id: A valid media ID.
- get_media_response_body: The response body from a GET request to the media entity's endpoint.
Returns:
The media type of the media entity (e.g., 'image'), None if it could not be found.
"""
try:
return get_media_response.json()['bundle'][0]['target_id']
except Exception as e:
logging.error("Unable to get media type for media ID %s. Reason %s", media_id, e)
def get_media_parent_node_id(get_media_response_body: dict, media_csv_row: dict) -> Optional[str]:
"""Get the parent node ID of the media entity.
Parameters:
- get_media_response_body: The response body from a GET request to the media entity's endpoint.
- media_csv_row: The CSV row containing the media entity's field names and values.
Returns:
The parent node's ID if it corresponds to a valid node, otherwise None.
NOTE: If node_id is specified in the CSV row, that value will be returned. Otherwise, the first node ID in the list of nodes the media entity is attached to will be returned.
"""
if 'node_id' in media_csv_row: # If the CSV row contains a node ID, it takes precedence
if media_csv_row['node_id']: # If the CSV row is not blank
return media_csv_row['node_id']
if not get_media_response_body['field_media_of']: # If the media entity is not attached to any node
logging.error("Media ID %s is not attached to any node, which is a requirement for updating media files.", media_id)
return None
try:
return get_media_response_body['field_media_of'][0]['target_id'] # Return the first node ID in the list of nodes the media entity is attached to
except Exception as e:
logging.error("Unable to get parent node ID for media ID %s. Reason %s", media_id, e)
return None
def patch_plain_text_fields(config: dict, media_type: str, media_csv_row: dict) -> dict:
"""Create the JSON request to be sent to the media entity's PATCH endpoint for updating plain-text fields.
Parameters:
- config (dict): The global configuration object.
- media_type (str): The media entity's type (e.g., 'image').
- media_csv_row (dict): The CSV row containing the media entity's field names and values.
Returns:
- The JSON request (dict) to be sent to the media entity's PATCH endpoint.
"""
media_json = {}
media_field_definitions = get_field_definitions(config, 'media', media_type) # This will return a dict of field definitions keyed by field name.
for field_name, field_value in media_csv_row.items(): # Iterate through the CSV row's field names and values and find the fields that are plain-text.
if field_name in media_field_definitions: # If the field name is a valid field name for the media entity's type
if 'string' in media_field_definitions[field_name]['field_type']: # If field_name corresponds to a plain-text field. In Drupal 8, plain-text fields contain 'string' in their type.
if field_value != '': # If the field value is not empty
media_json[field_name] = [{'value': field_value}]
else:
if field_name != 'media_id' and field_name != 'media_use_tid': # Don't log a warning for media_id or media_use_tid, since they definitely exist.
logging.warning("Field %s is not a valid plain-text field for media %s. This may be intended, but if not, please check the spelling of this field name.",
field_name,
media_type)
return media_json
def extract_media_id(config: dict, media_csv_row: dict) -> Optional[str]:
"""Extract the media entity's ID from the CSV row.
Parameters:
- config: The global configuration object.
- media_csv_row: The CSV row containing the media entity's field names and values.
Returns:
- The media entity's ID if it could be extracted from the CSV row and is valid, otherwise None.
"""
if 'media_id' not in media_csv_row: # Media ID column is missing
logging.error('Media ID column missing in CSV file.')
return None
if not media_csv_row['media_id']: # Media ID column is present but empty
logging.error('Row with empty media_id column detected in CSV file.')
return None
if not value_is_numeric(media_csv_row['media_id']): # If media ID is not numeric, assume it is a media URL alias
media_id = get_mid_from_media_url_alias(config, media_csv_row['media_id']) # Note that this function returns False if the media URL alias does not exist
if media_id is False: # Media URL alias does not exist
logging.error('Media URL alias %s does not exist.', media_csv_row['media_id'])
return None
else:
return str(media_id)
else: # If media ID is numeric, use it as is, if it is a valid media ID
if ping_media(config, media_csv_row['media_id']) != 200: # Invalid media ID
logging.error('Media ID %s does not exist.', media_csv_row['media_id'])
return None
else:
return media_csv_row['media_id'] # If media ID exists, use it as is (since this is a string)
def delete_media_file(config: dict, media_id: str, get_media_response_body: dict) -> bool:
"""Delete file attached to the media entity.
Parameters:
- config: The global configuration object.
- media_id: A valid media entity ID.
- get_media_response_body: The response body from a GET request to the media entity's endpoint.
Returns:
True if the file was successfully deleted or if there was no file attached to this media, False otherwise.
"""
# Inspect the JSON response to get the file ID
for file_field_name in file_fields:
if file_field_name in get_media_response_body:
try:
file_to_delete = str(get_media_response_body[file_field_name][0]['target_id'])
except Exception as e:
logging.warning("Unable to get file ID for media %s (reason: %s). Assuming there was no file attached to this media in the first place.", media_id, e)
return True
break
if file_to_delete:
# Now we delete the file
if config['standalone_media_url'] is True:
file_endpoint = config['host'] + '/entity/file/' + file_to_delete + '?_format=json'
else:
file_endpoint = config['host'] + '/entity/file/' + file_to_delete + '/edit?_format=json'
file_response = issue_request(config, 'DELETE', file_endpoint)
if file_response.status_code == 204:
logging.info("File %s (from media %s) deleted.", file_to_delete, media_id)
return True
else:
logging.error("File %s (from media %s) not deleted (HTTP response code %s). Assuming there was no file and attempting to add new file.",
file_to_delete, media_id,
file_response.status_code)
return False
def delete_media_track_files(config: dict, media_id: str, media_type: str, get_media_response_body: dict) -> bool:
"""Delete the track file file attached to the media entity.
Parameters:
- config: The global configuration object.
- media_id: A valid media entity ID.
- media_type: The media entity's type.
- get_media_response_body: The response body from a GET request to the media entity's endpoint.
Returns:
True if the track file was successfully deleted or if there were no track files in the first place, False otherwise.
"""
# Inspect the JSON response to get the file ID
if config['media_track_file_fields'][media_type] in get_media_response_body:
for track_file in get_media_response_body[config['media_track_file_fields'][media_type]]:
try:
file_to_delete = str(track_file['target_id'])
except Exception as e: # There is a track file attached to this media, but we can't get its ID
logging.warning("Unable to get track file ID for a track file attached to media ID %s (reason: %s).", media_id, e)
return False
if config['standalone_media_url'] is True:
file_endpoint = config['host'] + '/entity/file/' + file_to_delete + '?_format=json'
else:
file_endpoint = config['host'] + '/entity/file/' + file_to_delete + '/edit?_format=json'
file_response = issue_request(config, 'DELETE', file_endpoint)
if file_response.status_code == 204:
logging.info("Track File %s (from media %s) deleted.", file_to_delete, media_id)
else:
logging.error("Track File %s (from media %s) not deleted (HTTP response code %s).", file_to_delete, media_id, file_response.status_code)
return False
return True
else:
logging.warning("Unable to find track files for media ID %s. Proceeding and assuming there were no track files to begin with.", media_id)
return True
def attach_file_to_media(config: dict, media_type: str, file_id: str) -> dict:
"""Return the JSON object for a PATCH request required to attach the file to the media entity.
Parameters:
- config: The global configuration object.
- media_type: The media entity's type (e.g., 'image').
- file_id: A valid file entity ID.
Returns:
The JSON request for a PATCH request required to attach the file to the media entity.
"""
media_field = config['media_type_file_fields'][media_type] # Get the name of the field that corresponds to the media type (e.g. 'field_media_image' for media type 'image')
return {
media_field: [
{
'target_id': file_id,
'target_type': 'file',
}
]
}
def attach_track_files_to_media(config: dict, media_type: str, track_label_list: str, track_type_list: str, track_language_list: str, file_id_list: str) -> dict:
""" Return the JSON object for a PATCH request required to attach the track files and their information to a media entity.
Parameters:
- config: The global configuration object.
- media_type: The media entity's type (e.g., 'image').
- track_label_list: A list of track labels.
- track_type_list: A list of track types.
- track_language_list: A list of track languages.
- file_id_list: A list of file IDs.
Returns:
The JSON request for a PATCH request required to attach the track files and their information to a media entity.
"""
# We use list comprehension to create the JSON object that contains the track files and their information.
return {
config['media_track_file_fields'][media_type]: [
{
'target_id': file_id_list[i],
'label': track_label_list[i],
'kind': track_type_list[i],
'srclang': track_language_list[i],
'target_type': 'file',
}
for i in range(len(file_id_list))
]
}
def patch_media_use_terms_update_media(media_use_tids):
"""Return the JSON object for a PATCH request required to patch the media entity's media use terms.
Note: workbench_utils has its own patch_media_use_terms().
Parameters:
- media_use_tids: A list of taxonomy term IDs to patch to the media entity's field_media_use.
Returns:
The JSON request for a PATCH request required to patch the media entity's media use terms.
"""
return {
'field_media_use': [
{
'target_id': media_use_tid,
'target_type': 'taxonomy_term'
}
for media_use_tid in media_use_tids
]
}
def patch_media_status(status: bool) -> dict:
"""Return the JSON object for a PATCH request required to patch the media entity's "Published" status.
Parameters:
- status: True if the media entity should be published, False otherwise.
Returns:
The JSON request for a PATCH request required to patch the media entity's "Published" status, or None if the status is not a boolean.
"""
return {
'status': [
{'value': status}
]
}
# ========================================================= Main Logic =========================================================
# TODO: Updating the media file and the name simultaneously does not work. The media takes the name of the new file and not the specified name.
message = '"Update media" task started using config file ' + args.config + '.'
print(message)
logging.info(message)
csv_data = get_csv_data(config)
if config['id_field'] not in csv_data.fieldnames: # If the CSV file does not contain the ID field, we use the media ID field by default
config['id_field'] = 'media_id'
row_count = 0
for row in csv_data:
media_id = extract_media_id(config, row) # Extract the media ID from the CSV row
if media_id is None: # If the media ID is invalid, skip this row
row_count += 1
print("There are errors for CSV row " + str(row_count) + ". Please check the log for more details.")
if config['progress_bar'] is True:
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
continue
# At this point, the media ID is valid and stored in the media_id variable.
# Now, the user may want to update one or more of the following
# - Media File
# - Track File
# - Media Use TID
# - Published status
# - Plain text fields pertaining to the media.
# We'll need the GET response for this media on multiple occasions.
if config['standalone_media_url'] is True:
media_json_url = config['host'] + '/media/' + media_id + '?_format=json'
else:
media_json_url = config['host'] + '/media/' + media_id + '/edit?_format=json'
get_media_response = issue_request(config, 'GET', media_json_url)
get_media_response_body = json.loads(get_media_response.text)
# From this we can get the media type, which we'll need as well
media_type = get_media_type(media_id, get_media_response)
if media_type is None: # If the media type is invalid, skip this row.
row_count += 1
print('Media at ' + config['host'] + '/media/' + media_id + ' could not be updated. Please check the log for more details.')
if config['progress_bar'] is True:
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
continue
# We'll store the JSON for the patch request in this dictionary (which will grow as we add more fields to update).
patch_request_json = {'bundle': [{'target_id': media_type}]}
# Update media file
if 'file' in row and row['file'] != '':
# We need to first get the parent node ID of this media.
node_id = get_media_parent_node_id(get_media_response_body, row)
if node_id is None: # If the node ID is invalid, skip this row.
row_count += 1
print('Media at ' + config['host'] + '/media/' + media_id + ' could not be updated. Please check the log for more details.')
if config['progress_bar'] is True:
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
continue
# At this point we have the node ID of the parent node of the media.
# We use this with the create_file function to create the media file on the server.
file_id = create_file(config, row['file'], 'file', row, node_id)
if file_id is False or file_id is None: # If the file ID is invalid, skip this row.
logging.error('Failed to create file for media ID ' + media_id + '. Skipping this row.')
row_count += 1
print('Media at ' + config['host'] + '/media/' + media_id + ' could not be updated. Please check the log for more details.')
if config['progress_bar'] is True:
row_position = get_percentage(row_count, num_csv_records)
pbar(row_position)
continue