-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_manager.py
1719 lines (1245 loc) · 72.8 KB
/
data_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from BrainAnnex.modules.neo_schema.neo_schema import NeoSchema
from BrainAnnex.modules.categories.categories import Categories
from BrainAnnex.modules.PLUGINS.notes import Notes
from BrainAnnex.modules.PLUGINS.documents import Documents
from BrainAnnex.modules.upload_helper.upload_helper import UploadHelper
from BrainAnnex.modules.media_manager.media_manager import MediaManager, ImageProcessing
from BrainAnnex.modules.full_text_indexing.full_text_indexing import FullTextIndexing
from BrainAnnex.modules.py_graph_visual.py_graph_visual import PyGraphVisual
import re # For REGEX
import pandas as pd
import os
from flask import request, current_app # TODO: phase out (?)
from typing import Union
import shutil
import requests
import html
from datetime import datetime
"""
MIT License. Copyright (c) 2021-2024 Julian A. West BrainAnnex.org
"""
class DataManager:
"""
For general, high-level database-interaction operations.
Used by the UI for Page Generation,
as well as by the web API to produce data for the endpoints.
This library is primarily a common entry point for data requests:
many specific operations get delegated to other, more specialized, libraries.
This class does NOT get instantiated.
"""
# The "db" and several other class properties get set by InitializeBrainAnnex.set_dbase()
db = None # Object of class "NeoAccess". MUST be set before using this class!
LOG_FOLDER = None # Location where the log file is stored
ongoing_data_intake = False
import_file_count = 0
log_filename = "IMPORT_LOG.txt" # TODO: generalize to BrainAnnex-wide
log_file_handle = None
####################### LOW-LEVEL DATABASE-NODE UTILITIES #######################
@classmethod
def get_node_labels(cls) -> [str]:
"""
Look up and return a list of all the node labels in the database.
EXAMPLE: ["my_label_1", "my_label_2"]
:return: A list of strings
"""
label_list = cls.db.get_labels() # Fetch all the node labels in the database
return label_list
@classmethod
def add_new_label(cls, label: str) -> int:
"""
Create a new blank node with the specified label.
Mostly used for testing.
:return: The internal database ID of the new node
"""
return cls.db.create_node(label)
#####################################################################################################
''' ~ UTILITIES ~ '''
def ________UTILITIES________(DIVIDER):
pass # Used to get a better structure view in IDEs
#####################################################################################################
@classmethod
def to_int_if_possible(cls, s: str) -> Union[int, str, None]:
"""
Convert the argument to an integer, if at all possible; otherwise, leave it as a string
(or leave it as None, if applicable)
:param s: Value to convert to integer, if possible
:return: Either an int or a string
"""
try:
return int(s)
except ValueError:
return s
@classmethod
def str_to_int(cls, s: str) -> int:
"""
Helper function to give more friendly error messages in case non-integers are passed
in situations where integers are expected.
Without this function, the user would see cryptic messages such as
"invalid literal for int() with base 10: 'q123'"
EXAMPLE of usage:
try:
i = cls.str_to_int(i_str)
except Exception as ex:
# Do something
:param s: A string that should represent an integer
:return: The integer represented in the passed string, if applicable;
if not, an Exception is raised
"""
#TODO: no longer being used. Perhaps eliminate
try:
i = int(s)
except Exception:
raise Exception(f"The passed parameter ({s}) is not an integer as expected")
return i
@classmethod
def experimental_par_dict_cleaner(cls, data_dict, required_par_list=None, int_list={}) -> dict:
"""
NOT IN CURRENT USE YET
TODO: test, and start using
"Cleaner" for general dictionaries of parameters
:param data_dict: A generic dictionary of parameters
:param required_par_list: List of names of keys whose presence is required
:param int_list: List of names of keys whose values need to be integers
:return:
"""
if required_par_list:
for par in required_par_list:
assert par in data_dict, f"The expected parameter `{par}` is missing from the data"
for key, val in data_dict.items():
if val in int_list:
try:
val = int(val)
except Exception:
raise Exception(f"The passed parameter `{key}` is not an integer as expected; its value ({val} is of type {type(val)}")
elif type(val) == str:
val = val.strip()
data_dict[key] = val
return data_dict
#####################################################################################################
''' ~ SCHEMA-RELATED ~ '''
def ________SCHEMA_RELATED________(DIVIDER):
pass # Used to get a better structure view in IDEs
#####################################################################################################
# TODO: possibly move to separate class, such as NeoSchema
@classmethod
def all_schema_classes(cls) -> [str]:
"""
Return a list of all the existing Schema classes
:return:
"""
return NeoSchema.get_all_classes()
@classmethod
def get_schema_visualization_data(cls):
"""
Create and return an object with all the info
to visualise a graph with the database Schema info
:return: An object of class PyGraphScape
"""
graph_obj = PyGraphVisual(cls.db)
'''
# TODO: turn this simple example into a tutorial
graph_obj.add_node(node_id=1, labels=["PERSON", "OWNER"], data={"name": "Julian"})
graph_obj.add_node(node_id=2, labels=["VEHICLE", "CAR"], data={"color": "white", "year": 2003})
graph_obj.add_edge(from_node=1, to_node=2, name="OWNS")
graph_obj.assign_color_mapping(label="PERSON", color="cyan")
graph_obj.assign_color_mapping(label="OWNER", color="red")
graph_obj.assign_color_mapping(label="CAR", color="orange")
graph_obj.assign_caption(label="PERSON", caption="name")
graph_obj.assign_caption(label="CAR", caption="color")
graph_obj.assign_caption(label="VEHICLE", caption="year")
return graph_obj
'''
classes_match = cls.db.match(labels="CLASS")
schema_nodes = cls.db.get_nodes(match=classes_match,
return_internal_id=True, return_labels=True)
class_node_ids = graph_obj.prepare_graph(schema_nodes, add_edges=True)
#print("Class node IDs:", class_node_ids)
property_match = cls.db.match(labels="PROPERTY")
schema_nodes = cls.db.get_nodes(match=property_match,
return_internal_id=True, return_labels=True)
property_node_ids = graph_obj.prepare_graph(schema_nodes, add_edges=False)
#print("Property node IDs:", property_node_ids)
graph_obj.link_node_groups(class_node_ids, property_node_ids)
graph_obj.assign_color_mapping(label="CLASS", color="graph_darkgreen")
graph_obj.assign_color_mapping(label="PROPERTY", color="graph_orange")
graph_obj.assign_caption(label="CLASS", caption="name")
graph_obj.assign_caption(label="PROPERTY", caption="name")
return graph_obj # TODO: return a dict instead - use the serialize() method
@classmethod
def new_schema_class(cls, class_specs: dict) -> None:
"""
Create a new Schema Class, possibly linked to another existing class,
and also - typically but optionally - with the special "INSTANCE_OF" link
to an existing class (often, "Records")
In case of error, an Exception is raised.
:param class_specs: A dictionary with the following
DICTIONARY KEYS:
new_class_name The name of the new Class (tolerant of leading/trailing blanks)
properties_list The name of all desired Properties, in order
(all comma-separated). Tolerant of leading/trailing blanks, and of missing property names
instance_of Typically, "Records"
[ALL THE REMAINING KEYS ARE OPTIONAL]
linked_to The name of an existing Class node, to link to
rel_name The name to give to the above relationship
rel_dir The relationship direction, from the point of view of the newly-added node
:return: None
"""
new_class_name = class_specs["new_class_name"]
new_class_name = new_class_name.strip()
print("new_class_name: ", new_class_name)
properties_str = class_specs.get("properties_list", "") # Make allowance for an absent properties_list
property_list = properties_str.split(",") # Note: if properties_str is an empty string, the result will be ['']
print("property_list: ", property_list)
# Zap missing property names, and clean up the names that are present
property_list_clean = []
for p in property_list:
prop_name = p.strip()
if prop_name:
property_list_clean.append(prop_name)
print("property_list_clean: ", property_list_clean)
instance_of_class = class_specs.get('instance_of') # Will be None if key is missing
print(f"For 'INSTANCE_OF' relationship, requesting to link to Class: `{instance_of_class}`")
# Validate the optional relationship to another class
if ( ("linked_to" in class_specs) or ("rel_name" in class_specs) or ("rel_dir" in class_specs) ) \
and not \
( ("linked_to" in class_specs) and ("rel_name" in class_specs) and ("rel_dir" in class_specs) ):
raise Exception("The parameters `linked_to`, `rel_name` and `rel_dir` must all be present or all be missing")
# Create the new Class, and all of its Properties (as separate nodes, linked together)
new_id, _ = NeoSchema.create_class_with_properties(new_class_name, property_list_clean,
class_to_link_to=instance_of_class, link_name="INSTANCE_OF")
# If requested, link to another existing class
if ("linked_to" in class_specs) and ("rel_name" in class_specs) and ("rel_dir" in class_specs):
linked_to = class_specs["linked_to"]
#linked_to_id = NeoSchema.get_class_id(class_name = linked_to)
#print(f"Linking the new class to the existing class `{linked_to}`, which has ID {linked_to_id}")
print(f"Linking the new class to the existing class `{linked_to}`")
rel_name = class_specs["rel_name"]
rel_dir = class_specs["rel_dir"] # The link direction is relative to the newly-created class node
print(f"rel_name: `{rel_name}` | rel_dir: {rel_dir}")
assert rel_dir == "OUT" or rel_dir == "IN", f"The value for rel_dir must be either 'IN' or 'OUT' (passed value was {rel_dir})"
try:
if rel_dir == "OUT":
NeoSchema.create_class_relationship(from_class=new_id, to_class=linked_to, rel_name=rel_name)
elif rel_dir == "IN":
NeoSchema.create_class_relationship(from_class=linked_to, to_class=new_id, rel_name=rel_name)
except Exception as ex:
raise Exception(f"The new class `{new_class_name}` was created successfully, but could not be linked to `{linked_to}`. {ex}")
@classmethod
def add_schema_relationship_handler(cls, class_specs: dict) -> None:
"""
In case of error, an Exception is raised.
:param class_specs: A dictionary with the following
DICTIONARY KEYS:
from_class_name
to_class_name
rel_name
:return: None
"""
from_class_name = class_specs["from_class_name"]
from_class_name = from_class_name.strip()
#print("from_class_name: ", from_class_name)
to_class_name = class_specs["to_class_name"]
to_class_name = to_class_name.strip()
#print("to_class_name: ", to_class_name)
rel_name = class_specs["rel_name"]
rel_name = rel_name.strip()
#print("rel_name: ", rel_name)
NeoSchema.create_class_relationship(from_class=from_class_name, to_class=to_class_name, rel_name=rel_name)
@classmethod
def schema_add_property_to_class_handler(cls, specs_dict: dict) -> None:
"""
Add a new Property to an existing Classes
In case of error, an Exception is raised.
:param specs_dict: A dictionary with the following
DICTIONARY KEYS:
prop_name (any leading/trailing blanks are ignored)
class_name (any leading/trailing blanks are ignored)
:return: None
"""
prop_name = specs_dict.get("prop_name")
if not prop_name:
raise Exception("The expected parameter `prop_name` is missing from the data")
class_name = specs_dict.get("class_name")
if not class_name:
raise Exception("The expected parameter `class_name` is missing from the data")
# Locate the internal ID of the Class node
class_internal_id = NeoSchema.get_class_internal_id(class_name.strip())
number_prop_added = NeoSchema.add_properties_to_class(class_node= class_internal_id, property_list = [prop_name])
if number_prop_added != 1:
raise Exception(f"Failed to add the new Property `{prop_name}` to the Class `{class_name}` (internal ID {class_internal_id})")
@classmethod
def delete_schema_relationship_handler(cls, class_specs: dict) -> None:
"""
Delete the relationship(s) with the specified name
between the 2 existing Class nodes (identified by their respective names),
going in the from -> to direction direction.
In case of error, an Exception is raised.
:param class_specs: A dictionary with the following
DICTIONARY KEYS:
from_class_name
to_class_name
rel_name
:return: None
"""
from_class_name = class_specs["from_class_name"]
from_class_name = from_class_name.strip()
#print("from_class_name: ", from_class_name)
to_class_name = class_specs["to_class_name"]
to_class_name = to_class_name.strip()
#print("to_class_name: ", to_class_name)
rel_name = class_specs["rel_name"]
rel_name = rel_name.strip()
#print("rel_name: ", rel_name)
# Delete the relationship(s)
NeoSchema.delete_class_relationship(from_class=from_class_name, to_class=to_class_name, rel_name=rel_name)
####################### RECORDS-RELATED #######################
@classmethod
def add_data_relationship_handler(cls, data_dict: dict) -> None:
"""
Add the specified relationship (edge) between data nodes.
In case of error, an Exception is raised.
:param data_dict: A dictionary with the following
from The uri of the node from which the relationship originates
to The uri of the node into which the relationship takes
rel_name The name of the relationship to add
schema_code (optional) If passed, the appropriate plugin gets invoked
:return: None
"""
from_id = data_dict['from']
to_id = data_dict['to']
rel_name = data_dict['rel_name']
schema_code = data_dict.get('schema_code') # Tolerant of missing values
if schema_code == "cat": # TODO: take this part away?
Categories.add_relationship_before(from_id=from_id, to_id=to_id,
rel_name=rel_name) # Category-specific action
# The adding of the relationship is done here
NeoSchema.add_data_relationship_OLD(from_id=from_id, to_id=to_id,
rel_name=rel_name, id_type="uri")
@classmethod
def remove_data_relationship_handler(cls, data_dict: dict) -> None:
"""
Remove the specified relationship (edge) between data nodes.
In case of error, an Exception is raised.
:param data_dict: A dictionary with the following
DICTIONARY KEYS:
from The uri of the node from which the relationship originates
to The uri of the node into which the relationship takes
rel_name The name of the relationship to remove
schema_code (optional) If passed, the appropriate plugin gets invoked
:return: None
"""
from_uri = data_dict['from']
to_uri = data_dict['to']
rel_name = data_dict['rel_name']
schema_code = data_dict.get('schema_code') # Tolerant of missing values
if schema_code == "cat":
Categories.remove_relationship_before(from_id=from_uri, to_id=to_uri,
rel_name=rel_name) # Category-specific action
NeoSchema.remove_data_relationship(from_uri=from_uri, to_uri=to_uri,
rel_name=rel_name, labels="BA")
@classmethod
def get_leaf_records(cls) -> [str]:
"""
Get all Classes that are, directly or indirectly, INSTANCE_OF the Class "Records",
as long as they are leaf nodes (with no other Class that is an INSTANCE_OF them.)
EXAMPLE: if the "Foreign Vocabulary" Class is an INSTANCE_OF the Class "Records",
and if "French Vocabulary" and "German Vocabulary" are instances of "Foreign Vocabulary",
then "French Vocabulary" and "German Vocabulary" (but NOT "Foreign Vocabulary")
would be returned
:return: A list of strings with the Class names
EXAMPLE:
["Cuisine Type","Entrees","French Vocabulary","German Vocabulary","Restaurants","Site Link"]
"""
return NeoSchema.get_class_instances("Records", leaf_only=True)
####################### CONTENT-ITEM RELATED #######################
@classmethod
def get_text_media_content(cls, uri :str, schema_code, public_required = False) -> str:
"""
Fetch and return the contents of a media item stored on a local file,
optionally requiring it to be marked as "public".
In case of error, raise an Exception
:param uri: A string identifying the desired Content Item, which ought to be text media
:param schema_code: TODO: maybe phase out
:param public_required: If True, the Content Item is returned only if has an the attribute "public: true"
:return: A string with the HTML text of the requested note;
or an Exception in case of failure
(e.g., if public_required is True and the item isn't public)
"""
properties = {"uri": uri, "schema_code": schema_code}
if public_required:
properties["public"] = True # Extend the match requirements
match = cls.db.match(labels="BA", properties=properties)
content_node = cls.db.get_nodes(match, single_row=True)
#print("content_node:", content_node)
if content_node is None: # Metadata not found
raise Exception(f"The metadata for the Content Item (uri: `{uri}`) wasn't found, or the items is not publicly accessible")
basename = content_node['basename']
suffix = content_node['suffix']
filename = f"{basename}.{suffix}"
folder = MediaManager.lookup_file_path(schema_code=content_node['schema_code']) # Includes the final "/"
try:
file_contents = MediaManager.get_from_text_file(folder, filename, encoding="utf8")
return file_contents
except Exception as ex:
return f"I/O failure while reading in contents of Item with URI `{uri}`. {ex}" # File I/O failed
@classmethod
def get_records_by_link(cls, request_data: dict) -> [dict]:
"""
Locate and return the data of the nodes linked to the one specified by uri,
by the relationship named by rel_name, in the direction specified by dir
:param request_data: A dictionary with 3 keys, "uri", "rel_name", "dir"
:return: A list of dictionaries with all the properties of the neighbor nodes
"""
uri = request_data["uri"] # This must be a string
rel_name = request_data["rel_name"]
dir = request_data["dir"] # Must be either "IN or "OUT"
assert dir in ["IN", "OUT"], \
f"get_records_by_link(): The value of the parameter `dir` must be either 'IN' or 'OUT'. The value passed was '{dir}'"
assert type(uri) == str, \
"get_records_by_link(): The value of the parameter `uri` must be an integer"
match = cls.db.match(labels="BA", key_name="uri", key_value=uri)
return cls.db.follow_links(match, rel_name=rel_name, rel_dir=dir, neighbor_labels ="BA")
@classmethod
def get_link_summary(cls, uri :str, omit_names = None) -> dict:
"""
Return a dictionary structure identifying the names and counts of all
inbound and outbound links to/from the given data node.
TODO: move most of it to the "~ FOLLOW LINKS ~" section of NeoAccess
:param uri: String with the URI of a data node
:param omit_names: Optional list of relationship names to disregard
:return: A dictionary with the names and counts of inbound and outbound links.
Each inner list is a pair [name, count]
EXAMPLE:
{
"in": [
["BA_served_at", 1]
],
"out": [
["BA_located_in", 1],
["BA_cuisine_type", 2]
]
}
"""
if omit_names:
assert type(omit_names) == list, "If the `omit_names` argument is specified, it MUST be a LIST"
where_clause = f"WHERE NOT type(r) IN {omit_names}"
else:
where_clause = ""
# Get outbound links (names and counts)
q_out = f'''
MATCH (n :BA {{uri:$uri}})-[r]->(n2 :BA)
{where_clause}
RETURN type(r) AS rel_name, count(n2) AS rel_count
'''
result = cls.db.query(q_out, data_binding={"uri": uri})
rel_out = [ [ l["rel_name"],l["rel_count"] ] for l in result ]
# Get inbound links (names and counts)
q_in = f'''
MATCH (n :BA {{uri:$uri}})<-[r]-(n2 :BA)
{where_clause}
RETURN type(r) AS rel_name, count(n2) AS rel_count
'''
result = cls.db.query(q_in,data_binding={"uri": uri})
rel_in = [ [ l["rel_name"],l["rel_count"] ] for l in result ]
return {"in": rel_in, "out": rel_out}
############## MODIFYING CONTENT ITEMS ##############
@classmethod
def update_content_item(cls, post_data: dict) -> None:
"""
Update an existing Content Item.
In case of error, an Exception is raised
NOTE: the "schema_code" field is currently required, but it's redundant. Only
used as a safety mechanism against incorrect values of the URI
(TODO: maybe ditch, or use the Class name instead)
:return: None. In case of error, an Exception is raised
"""
#TODO: if any (non-special?) field is blank, drop it altogether from the node;
# maybe add this capability to set_fields()
#print("In update_content_item(). POST dict: ", post_data)
# Validate the data
schema_code = post_data.get("schema_code") # If key not present, the value will be None
#print("Item Type: ", schema_code)
uri = post_data.get("uri")
assert uri, "update_content_item(): a value for `uri` is missing from the POST data"
#print("Item Type: ", uri)
data_binding = post_data
set_dict = {} # Dictionary of field values to set
for k, v in data_binding.items():
if k not in ("schema_code", "uri"): # Exclude some special keys
set_dict[k] = v
# First, make sure that the requested Content Item exists.
# TODO: get assistance from Schema layer. Try:
# assert NeoSchema.data_node_exists(data_node=uri), f"update_content_item(): no Content Item found with URI `{uri}` and Schema Code '{schema_code}'
match = cls.db.match(labels="BA", properties={"uri": uri, "schema_code": schema_code})
records = cls.db.get_nodes(match)
assert records != [], f"update_content_item(): no Content Item found with URI `{uri}` and Schema Code '{schema_code}'"
# PLUGIN-SPECIFIC OPERATIONS that *change* set_dict and perform filesystem operations
# TODO: try to infer them from the Schema
original_post_data = post_data.copy() # Clone an independent copy of the dictionary - that won't be affected by changes to the original dictionary
# TODO: instead of passing along in the POST request things like `basename` and `suffix`
# (which place a burden on the front end),
# get them from the database, and just pass all the node attributes to the plugin-specific modules
# Try:
# db_data = NeoSchema.fetch_data_node(uri=uri)
# Then pass db_data as a parameter to the plugin-specific modules
if schema_code == "n":
if data_binding.get("basename") == "undefined":
raise Exception("update_content_item(): attempting "
"to pass a `basename` attribute to the value 'undefined'")
set_dict = Notes.before_update_content(data_binding, set_dict)
# Update, possibly adding and/or dropping fields, the properties of the existing Data Node
#internal_dbase_id = NeoSchema.get_data_node_internal_id(uri) # TODO: this will become unnecessary after switching to string uri's
#number_updated = NeoSchema.update_data_node(data_node=internal_dbase_id, set_dict=set_dict, drop_blanks=True)
number_updated = NeoSchema.update_data_node(data_node=uri, set_dict=set_dict, drop_blanks=True)
if schema_code == "n":
Notes.update_content_item_successful(uri, original_post_data)
# If the update was NOT for a "note" (in which case it might only be about the note's body than its metadata)
# verify that some fields indeed got changed
if schema_code != "n" and number_updated == 0:
raise Exception("No update performed")
@classmethod
def delete_content_item(cls, uri: str, schema_code: str) -> None:
"""
Delete the specified individual Content Item.
Note that schema_code is redundant.
In case of error, an Exception is raised
:param uri: String version of the unique ID
:param schema_code: Redundant
:return: None. In case of error, an Exception is raised
"""
#print(f"In delete_content_item(). Attempting to delete URI `{uri}` of type `{schema_code}`")
assert uri, "delete_content_item(): argument `uri` is missing"
# First, make sure that the requested Content Item exists. TODO: get assistance from Schema layer
match = cls.db.match(labels="BA", properties={"uri": uri, "schema_code": schema_code})
records = cls.db.get_nodes(match)
assert records != [], f"delete_content_item(): no Content Item found with URI `{uri}` and Schema Code '{schema_code}'"
# PLUGIN-SPECIFIC OPERATIONS (often involving changes to files)
# (TODO: try to infer that from the Schema)
if schema_code in ["n", "i", "d"]:
# If there's media involved, delete the media, too
record = cls.lookup_media_record(uri)
if record is not None:
MediaManager.delete_media_file(record["basename"], record["suffix"], schema_code)
if schema_code == "i":
# TODO: move this to the Images plugin, which should provide an Images.delete_content_before() method
# Extra processing for the "Images" plugin (for the thumbnail images)
record = cls.lookup_media_record(uri)
if record is not None:
MediaManager.delete_media_file(record["basename"], record["suffix"], schema_code, thumbs=True)
if schema_code == "n":
Notes.delete_content_before(uri)
# Perform the actual deletion of the Content Item node
number_deleted = cls.db.delete_nodes(match) # TODO: switch to using the Schema layer
if number_deleted == 1:
if schema_code == "n":
# Extra processing for the "Notes" plugin
Notes.delete_content_successful(uri) # Not actually needed for notes, but setting up the general system
return # Successful termination, with 1 Content Item deleted, as expected
elif number_deleted == 0:
raise Exception(f"Unable to delete Content Item id {uri} of type `{schema_code}`") # Error message (nothing deleted)
else:
raise Exception(f"{number_deleted} Content Items deleted, instead of the expected 1") # Error message (too much deleted)
# Should not happen, since uri is a primary key
@classmethod
def new_content_item_in_category(cls, post_data: dict) -> str:
"""
Create a new Content Item attached to a particular Category,
at a specified position on the Category page
:param post_data: A dict containing the following keys
- "category_id" (for the linking to a Category)
- Schema-related keys:
* schema_code (Required)
* schema_uri (Optional)
* class_name (Required only for Class Items of type "record")
- insert_after Either a URI of an existing Content Item attached to this Category,
or one of the special values "TOP" or "BOTTOM"
- *PLUS* all applicable plugin-specific fields (all the key/values for the new Content Item)
:return: The URI of the newly-created Data Node.
In case of error, an Exception is raised
"""
# NOTE: the post_data dictionary contains entries are not part of the data dictionary for the new Content Item;
# those will be eliminated below
# Validate the data, and extract some special attributes, while also paring down the post_data dictionary
# TODO: give better error messages; for example, if the requested Category doesn't exist
# TODO: possibly generalize from "Category" to "Collection"
# Category-related data
category_id = post_data.get("category_id") # If the key isn't present, the value will be None
if not category_id:
raise Exception("Missing Category ID")
del post_data["category_id"] # Remove this entry from the dictionary
# Positioning within the Category
insert_after = post_data.get("insert_after")
if not insert_after:
raise Exception("Missing insert_after (URI of Item to insert the new one after)")
del post_data["insert_after"]
# Schema-related data
schema_code = post_data.get("schema_code")
if not schema_code:
raise Exception("Missing Schema Code (Item Type)")
del post_data["schema_code"]
schema_uri = post_data.get("schema_uri") # TODO: ditch using the schema_uri, in favor of class_name
if schema_uri:
del post_data["schema_uri"]
else:
schema_uri = NeoSchema.get_schema_uri(schema_code) # If not passed, try to look it up
print("schema_uri looked up as: ", schema_uri)
if schema_uri == "":
raise Exception(f"Missing Schema URI for schema_code `{schema_code}`")
class_name = post_data.get("class_name")
if class_name:
del post_data["class_name"]
else:
# If not provided, look it up from the schema_uri
class_name = NeoSchema.get_class_name_by_schema_uri(schema_uri)
print(f"class_name looked up as: `{class_name}`")
# Generate a new ID (which is needed by some plugin-specific modules)
new_uri = NeoSchema.reserve_next_uri() # TODO: switch to using specific namespaces
print(f"New item will be assigned URI: '{new_uri}'")
# PLUGIN-SPECIFIC OPERATIONS that change data_binding and perform filesystem operations
# TODO: try to infer them from the Schema
# E.g., the Schema indicates that 2 Properties, "basename" and "suffix" are required;
# a call is made to a plugin-specific module, to produce those (and, in the process,
# some files are saved,
# some attributes are added to post_data, and some are whisked away)
# Note: the plugin might want to do some ops regardless of missing required Properties
# TODO: invoke the plugin-specified code PRIOR to removing fields from the POST data
original_post_data = post_data.copy() # Clone an independent copy of the dictionary - that won't be affected by changes to the original dictionary
if schema_code == "n":
post_data = Notes.add_content(new_uri, post_data)
print("Revised post_data: ", post_data)
# EXAMPLE: {'text': 'My New Header'}
# Note that several entries got removed from the dictionary;
# only the attributes that will go into the new node are still present.
# Some attributes may have been added by a plugin-specific module
if post_data.get("basename") == "undefined": # TODO: maybe extend to ALL fields being set!
raise Exception("new_content_item_in_category(): attempting "
"to set a `basename` attribute to the value 'undefined'")
# Create the new node and required relationships
if insert_after == "TOP":
Categories.add_content_at_beginning(category_uri=category_id,
item_class_name=class_name, item_properties=post_data,
new_uri=new_uri)
elif insert_after == "BOTTOM":
Categories.add_content_at_end(category_uri=category_id,
item_class_name=class_name, item_properties=post_data,
new_uri=new_uri)
else: # Insert at a position that is not the top nor bottom
Categories.add_content_after_element(category_uri=category_id,
item_class_name=class_name, item_properties=post_data,
insert_after=insert_after, new_uri=new_uri)
# A final round of PLUGIN-SPECIFIC OPERATIONS
if schema_code == "n":
Notes.new_content_item_successful(new_uri, original_post_data)
return new_uri # Success
@classmethod
def new_content_item_in_category_final_step(cls, insert_after :str, category_id :str, new_uri, class_name,
post_data, original_post_data):
# TODO: NOT YET IN USE
# Meant to take over the final parts of BA_Api_Routing.upload_media() and DataManager.new_content_item_in_category()
# Create the new node and required relationships
if insert_after == "TOP":
Categories.add_content_at_beginning(category_uri=category_id,
item_class_name=class_name, item_properties=post_data,
new_uri=new_uri)
elif insert_after == "BOTTOM":
Categories.add_content_at_end(category_uri=category_id,
item_class_name=class_name, item_properties=post_data,
new_uri=new_uri)
else: # Insert at a position that is not the top nor bottom
Categories.add_content_after_element(category_uri=category_id,
item_class_name=class_name, item_properties=post_data,
insert_after=insert_after, new_uri=new_uri)
# A final round of PLUGIN-SPECIFIC OPERATIONS
if class_name == "Notes":
Notes.new_content_item_successful(new_uri, original_post_data)
elif class_name == "Documents":
Documents.new_content_item_successful(new_uri, original_post_data, mime_type='text/plain') #TODO: check the MIME type
#####################################################################################################
''' ~ CATEGORY-RELATED (incl. adding new Content Items) ~ '''
def ________CATEGORY_RELATED________(DIVIDER):
pass # Used to get a better structure view in IDEs
#####################################################################################################
@classmethod
def switch_category(cls, data_dict) -> None:
"""
Switch one or more Content Items from being attached to a given Category,
to another one
:param data_dict: Dict with 3 keys:
items list of string URI's of Content Items
to relocate across Categories
from URI of the old Category
to URI of the new Category
:return: None
"""
#print("**** : ", data_dict) # EXAMPLE: {'items': ['i-3332', 'i-3278'], 'from': '3676', 'to': '3677'}
items = data_dict["items"]
assert type(items) == list, \
f"The passed POST value `items` ({items}) doesn't evaluate to a list"
assert type(data_dict['from']) == str, \
f"The passed POST value `from` ({data_dict['from']}) doesn't evaluate to a string"
assert type(data_dict['to']) == str, \
f"The passed POST value `from` ({data_dict['to']}) doesn't evaluate to a string"
number_items = len(items)
assert number_items != 0, \
f"The passed POST value `items` is an EMPTY list"
number_moved = Categories.relocate_across_categories(items=items,
from_category=data_dict['from'],
to_category=data_dict['to'])
assert number_moved != 0, \
f"None of the {number_items} requested " \
f"Content Item(s) could be successfully moved across Categories"
assert number_moved == number_items, \
f"Only {number_moved} of the {number_items} requested " \
f"Content Item(s) could be successfully moved across Categories"
#####################################################################################################
''' ~ MEDIA-RELATED ~ '''
def ________MEDIA_RELATED________(DIVIDER):
pass # Used to get a better structure view in IDEs
#####################################################################################################
@classmethod
def lookup_media_record(cls, uri: int) -> Union[dict, None]:
"""
Attempt to retrieve the metadata for the media file attached to the specified Content Item
TODO: move to MediaManager class
:param uri: An integer with the URI of the Content Item
:return: If found, return a dict with the record; otherwise, return None
"""
record = cls.db.get_record_by_primary_key("BA", "uri", uri)
if record is None:
return None
if ("basename" not in record) or ("suffix" not in record):
return None
return record
#####################################################################################################
''' ~ SEARCH ~ '''
def ________SEARCH________(DIVIDER):
pass # Used to get a better structure view in IDEs
#####################################################################################################
@classmethod
def search_for_terms(cls, words :str, search_category="") -> ([dict], str):
"""
Carry out a full-text search for a word, or set of words - possibly restricted to some Categories