-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
executable file
·1639 lines (1560 loc) · 55.6 KB
/
api.py
File metadata and controls
executable file
·1639 lines (1560 loc) · 55.6 KB
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
import json
import urllib.parse
import asyncio
import graphene
import requests
import responder
from dotenv import load_dotenv
from marshmallow import Schema, fields
from requests.auth import HTTPBasicAuth
from urllib.parse import urlparse
from starlette.responses import PlainTextResponse, RedirectResponse
import httpx
load_dotenv(verbose=True,override=True)
import logging
import os
import sys
import time
#from py2neo import Graph
from query import GraphQuery
from tools import generate_grapho_id
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create console handler and set level to debug
ch = logging.StreamHandler()
# ch.setLevel(logging._ExcInfoType)
# create formatter - simple or more detail as required
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
logger.propagate = False
from pathlib import Path
NEO4J_HOST = os.getenv('NEO4J_HOST')
NEO4J_USER = os.getenv('NEO4J_USER')
NEO4J_PASSWORD = os.getenv('NEO4J_PASSWORD')
NEO4J_PORT_HTTP = os.getenv('NEO4J_PORT_HTTP')
NEO4J_PORT_BOLT = os.getenv('NEO4J_PORT_BOLT')
NEO4J_DATABASE = os.getenv('NEO4J_DATABASE')
logger.debug(f"NEO4J_DATABASE is {NEO4J_DATABASE}")
PUBLIC_URL = os.getenv('PUBLIC_URL')
QUERY_LIMIT = os.getenv('QUERY_LIMIT')
INCLUDE_FIXED_QUERIES = eval(os.getenv('INCLUDE_FIXED_QUERIES',"False"))
INCLUDE_ADDITIONAL_DIALOGUE = eval(os.getenv('INCLUDE_ADDITIONAL_DIALOGUE',"False"))
LOG_LEVEL = os.getenv('LOG_LEVEL')
if LOG_LEVEL == "DEBUG":
logger.setLevel(logging.DEBUG)
ch.setLevel(logging.DEBUG)
# Fixed Queries are hardcoded here - aka "API Handles" that do not require parameters
# Grapho supports Handles stored in DB, API, UE Map, and overall Project
FIXED_QUERIES = [
# {
# "url": '{0}/top_betweenness/10'.format(
# PUBLIC_URL),
# "label": 'Top Betweenness',
# "slug": 'top_betweenness'
# },
{
"url": '{0}/up_next'.format(
PUBLIC_URL),
"label": 'Up Next',
"slug": 'Up Next'
}
# {
# "url": '{0}/top_node_similarity/10'.format(
# PUBLIC_URL),
# "label": 'Top Similarity',
# "slug": 'top_similarity'
# },
]
# logger.info(type(INCLUDE_FIXED_QUERIES))
API_TITLE = "Grapho XR API"
API_AUTHOR = "Michela Ledwidge"
API_PUBLISHER = "Mod Productions Pty Ltd."
API_COPYRIGHT = "All Rights Reserved"
API_VERSION = "1.7"
logger.info(f"{API_TITLE} v{API_VERSION} for Neo4j user {NEO4J_USER}")
logger.debug(f"LOG_LEVEL is {LOG_LEVEL}")
logger.debug(f"INCLUDE_FIXED_QUERIES is {INCLUDE_FIXED_QUERIES}")
if NEO4J_PORT_HTTP and int(NEO4J_PORT_HTTP) == 7474:
NEO4J_API = f"neo4j://{NEO4J_HOST}:{NEO4J_PORT_BOLT}"
logger.info(f"dev API instance\n{NEO4J_API}")
else:
NEO4J_API = f"neo4j+s://{NEO4J_HOST}:{NEO4J_PORT_BOLT}"
logger.info(f"live API instance\n{NEO4J_API}")
def is_url(value):
"""Check if value is a valid URL"""
try:
result = urlparse(value)
return all([result.scheme in ("http", "https"), result.netloc])
except Exception:
return False
async def calculate_total_content_length(data,type=""):
"""Calculate total content length from all media in endpoint response"""
total_content_length = 0
# for bespoke /all structure
if type == "handles":
logger.debug(f"Calculating total content length for {len(data)} handles")
for handle in data:
for node in handle['nodes']:
for property in node['properties'].keys():
if is_url(node['properties'][property]):
logger.debug(f"URL: {node['properties'][property]}")
async with httpx.AsyncClient() as client:
try:
response = await client.head(node['properties'][property])
# logger.debug(f"Response: {response.headers}")
size = int(response.headers.get('Content-Length', 0))
# logger.debug(f"Size: {size}")
total_content_length += size
except httpx.RequestError as e:
logger.warning(f"Request error for URL {node['properties'][property]}: {e}")
except httpx.HTTPStatusError as e:
logger.warning(f"HTTP error {e.response.status_code} for URL {node['properties'][property]}")
except ValueError as e:
logger.warning(f"Invalid Content-Length header for URL {node['properties'][property]}: {e}")
except Exception as e:
logger.warning(f"Unexpected error processing URL {node['properties'][property]}: {e}")
else:
# for Neo4j generic result syntax
logger.debug(f"Calculating total content length for {len(data)} nodes")
for node in data:
for property in node['properties'].keys():
if is_url(node['properties'][property]):
logger.debug(f"URL: {node['properties'][property]}")
async with httpx.AsyncClient() as client:
try:
response = await client.head(node['properties'][property])
# logger.debug(f"Response: {response.headers}")
size = int(response.headers.get('Content-Length', 0))
# logger.debug(f"Size: {size}")
total_content_length += size
except httpx.RequestError as e:
logger.warning(f"Request error for URL {node['properties'][property]}: {e}")
except httpx.HTTPStatusError as e:
logger.warning(f"HTTP error {e.response.status_code} for URL {node['properties'][property]}")
except ValueError as e:
logger.warning(f"Invalid Content-Length header for URL {node['properties'][property]}: {e}")
except Exception as e:
logger.warning(f"Unexpected error processing URL {node['properties'][property]}: {e}")
return total_content_length
api = responder.API(title=API_TITLE, enable_hsts=False, version=API_VERSION, openapi="3.0.0", docs_route="/docs", cors=True, cors_params={"allow_origins":["*"]})
@api.schema("PageSchema")
class PageSchema(Schema):
id = fields.Integer()
label = fields.Str()
source = fields.Str()
source_url = fields.URL()
image_url = fields.URL()
video_url = fields.URL()
archive_url = fields.URL()
archive_date = fields.DateTime()
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return f"Hello {name}"
schema = graphene.Schema(query=Query)
# view = GraphQLView(api=api, schema=schema)
# api.add_route("/graph", view)
pages = []
@api.route("/")
def hello_world(req, resp):
resp.content = api.template('index.html', who="")
@api.route("/hello/{who}/html")
def hello_html(req, resp, *, who):
resp.content = api.template('index.html', who=who)
@api.schema("HandleSchema")
class HandleSchema(Schema):
id = fields.Integer()
start_id = fields.Float()
label = fields.Str()
async def fetch_url(client, url):
logger.error(url)
response = await client.get(url)
return response.json()
async def fetch_all(urls):
logger.error(urls)
async with httpx.AsyncClient() as client:
tasks = [fetch_url(client, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
@api.route("/all/{db}")
async def api_all_database(req,resp,*,db):
"""All data for experience. Selection of database slug in API
---
get:
summary: All handles and fixed queries
description: Respond with all Handle nodes saved in database along with any fixed or parameterised queries hardcoded in API
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
"""
# resp.status_code = api.status_codes.HTTP_302
# resp.headers['Location'] = '/static/test.json'
graphs = []
DATABASE = db
# LOD sets default number of neighbours to include in handles
lod = 1 # default is 1
# if DATABASE == 'groove':
# lod = 2
handles_request = '{0}/handles/{1}'.format(PUBLIC_URL,DATABASE)
logger.debug(f'Handles API request: {handles_request}')
async with httpx.AsyncClient() as client:
try:
handles = await client.get(handles_request)
except Exception as e:
logger.error(f"Error fetching handles: {e} - check if PUBLIC_URL env variable ({PUBLIC_URL})is valid")
resp.status_code = 503
data = dict(
message="Invalid API request",
error_code=503
)
resp.media = data
return
try:
for handle in handles.json()['results'][0]['data'][0]['graph']['nodes']:
logger.debug(handle)
try:
label = handle['properties']['label']
except KeyError as e:
logger.error("TODO - fix dependency on label property")
label = handle['properties']['name']
try:
handle_id = int(handle['id'])
logger.warning(f"Neo4j integer id deprecated - need to change to string: {handle_id}")
handle_request = '{0}/handle/{1}/{2}/{3}'.format(
PUBLIC_URL, DATABASE,handle_id,lod)
# r = requests.get(handle_request)
# refactor for async
# handle_requests.append(handle_request)
logger.debug(f"handle_request: {handle_request}")
async with httpx.AsyncClient() as client2:
r = await client2.get(handle_request)
logger.debug(f"r: {r}")
except ValueError as ex:
handle_id = handle['id']
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logger.error(message)
logger.error(f"Neo4j 5 new id detected: {handle_id} - not ready to support yet")
handle_request = '{0}/handle'.format(
PUBLIC_URL)
logger.debug(f'Label: {label}')
logger.debug(f'Id: {handle_id}')
logger.debug(handle_request)
handle_data = {
'id': handle_id,
'db': DATABASE,
'lod': lod
}
r = requests.post(handle_request,json=handle_data)
g = r.json()['results'][0]['data'][0]['graph']
g['handle_id'] = handle_id
graphs.append(g)
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logger.warning(message)
resp.status_code = 503
data = dict(
message="Invalid API request",
error_code=503
)
resp.media = data
return
logger.debug("All handle queries complete")
handle_node_id = 100000 # HACK - instead of using DB generated id, create one for handles - DANGEROUS\
handle_relationship_id = 200000
if INCLUDE_FIXED_QUERIES: # ??? WHY not just if INCLUDE_FIXED_QUERIES
for f in FIXED_QUERIES:
handle_node_id = handle_node_id + 1
handle_relationship_id = handle_relationship_id + 1
logger.debug(f['url'])
r = requests.get(f["url"])
g = {}
nodes = []
relationships = []
try:
for subgraph in r.json()['results'][0]['data']:
for n in subgraph['graph']['nodes']:
nodes.append(n)
for r in subgraph['graph']['relationships']:
relationships.append(r)
handle_node = dict(
id=handle_node_id,
labels = ["Handle"],
properties= {
"label": f["label"],
"slug": f["slug"]
}
)
nodes.append(handle_node)
g["nodes"] = nodes
handle_relationship = dict(
id=handle_relationship_id,
type="NEXT",
startNode=handle_node_id,
endNode=nodes[0]['id'],
properties= {
}
)
relationships.append(handle_relationship)
g["relationships"] = relationships
g["handle_id"] = handle_node_id
graphs.append(g)
except TypeError:
logger.warning(f"Fixed Query error for {f['url']} - no 'results'")
try:
if 'node' in r.json()[0]:
logger.debug("Try to parse as GDS result")
for subgraph in r.json():
nodes.append(subgraph['node'])
# TODO fix break of DRY
handle_node = dict(
id=handle_node_id,
labels = ["Handle"],
properties= {
"label": f["label"],
"slug": f["slug"]
}
)
nodes.append(handle_node)
g["nodes"] = nodes
handle_relationship = dict(
id=handle_relationship_id,
type="NEXT",
startNode=str(handle_node_id),
endNode=str(nodes[0]['id']),
properties= {
}
)
relationships.append(handle_relationship)
g["relationships"] = relationships
g["handle_id"] = handle_node_id
graphs.append(g)
except TypeError:
logger.warning(f"Fixed Query error for {f['url']} - no 'node' (GDS) format")
logger.debug("All fixed queries complete")
if INCLUDE_ADDITIONAL_DIALOGUE:
async with httpx.AsyncClient() as client:
additional_dialogue_request = '{0}/dialogue/{1}'.format(PUBLIC_URL,DATABASE)
logger.debug(f"Additional dialogue API request: {additional_dialogue_request}")
dialogue = await client.get(additional_dialogue_request)
additional_dialogue=dialogue.json()['results'][0]['data'][0]['graph']['nodes']
logger.debug(f"Additional dialogue: {additional_dialogue}")
else:
additional_dialogue = []
logger.debug("All additional dialogue queries complete")
graphs_content_length = await calculate_total_content_length(graphs,'handles')
data = dict(
author=API_AUTHOR,
database=DATABASE,
url=PUBLIC_URL,
publisher=API_PUBLISHER,
copyright=API_COPYRIGHT,
graphs=graphs,
total_content_length=graphs_content_length,
additional_dialogue=additional_dialogue
)
# account for JSON size in total_content_length
json_bytes = json.dumps(data).encode('utf-8')
size_in_bytes = len(json_bytes) + graphs_content_length
data['total_content_length'] = size_in_bytes
resp.media = data
@api.route("/node/schema/{db}")
def api_node_schema(req,resp,*, db):
"""Return schema for database nodes
---
get:
summary: Respond with schema for database nodes
description: Respond with schema for database nodes
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
query = f"\
CALL apoc.meta.schema() yield value{chr(10)}\
UNWIND apoc.map.sortedProperties(value) as labelData{chr(10)}\
WITH labelData[0] as label, labelData[1] as data{chr(10)}\
WHERE data.type = 'node'{chr(10)}\
UNWIND apoc.map.sortedProperties(data.properties) as property{chr(10)}\
WITH label, property[0] as property, property[1] as propData{chr(10)}\
RETURN label,{chr(10)}\
property,{chr(10)}\
propData.type as type,{chr(10)}\
propData.indexed as isIndexed,{chr(10)}\
propData.unique as uniqueConstraint,{chr(10)}\
propData.existence as existenceConstraint"
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD,req, db)
graph = q.run(query,False)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except:
resp.status_code = 503
@api.route("/rel/schema/{db}")
def api_rel_schema(req,resp,*, db):
"""Return schema for database relationships
---
get:
summary: Respond with schema for database relationships
description: Respond with schema for database relationships
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"\
CALL apoc.meta.schema() yield value{chr(10)}\
UNWIND apoc.map.sortedProperties(value) as labelData{chr(10)}\
WITH labelData[0] as label, labelData[1] as data{chr(10)}\
WHERE data.type = 'relationship'{chr(10)}\
UNWIND apoc.map.sortedProperties(data.properties) as property{chr(10)}\
WITH label, property[0] as property, property[1] as propData{chr(10)}\
RETURN label,{chr(10)}\
property,{chr(10)}\
propData.type as type,{chr(10)}\
propData.indexed as isIndexed,{chr(10)}\
propData.unique as uniqueConstraint,{chr(10)}\
propData.existence as existenceConstraint"
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD,req, db)
graph = q.run(query,False)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except:
resp.status_code = 503
@api.route("/neighbours/{db}/{node_id}/{distance}")
async def api_neighbours(req,resp,*, db, node_id, distance):
"""Subgraph comprising neighbours of specified node.
---
get:
summary: Node neighbours
description: Respond with all feed values required for subgraph comprising neighbours of specified node.
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
- in: path
name: node_id
required: true
schema:
type: integer
minimum: 0
default: 1
description: The node ID (e.g. 1000)
- in: path
name: distance
required: true
schema:
type: integer
minimum: 1
default: 1
description: Distance of neighbours to node_id
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
distance=int(distance)
assert(1 <= distance <= 2)
query = f"\
MATCH (a)-[r*0..{distance}]-(neighbour){chr(10)}\
WHERE id(a) = {node_id} AND NOT neighbour:Handle{chr(10)}\
RETURN collect(distinct(neighbour)),r{chr(10)}\
LIMIT {QUERY_LIMIT}"
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD,req, db)
graph = q.run(query)
# logger.debug(f"Graph: {type(graph)}")
result = json.loads(graph)
# logger.debug(f"Result: {type(result)}")
path = result['results'][0]['data'][0]['graph']['nodes']
# logger.debug(f"Result graph for calculate_total_content_length: {path}")
result['total_content_length'] = await calculate_total_content_length(path)
json_str = json.dumps(result)
json_size = sys.getsizeof(json_str)
result['total_content_length'] += json_size
resp.media = result
resp.status_code = 200
q.close()
except Exception as e:
logger.error(e)
resp.status_code = 503
@api.route("/dialogue/{db}")
def api_dialogue(req,resp,*, db):
"""Subgraph comprising additional dialogue.
---
get:
summary: Dialogue nodes
description: Dialogue specific nodes only.
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"\
MATCH (a:Dialogue)\
RETURN a \
LIMIT {QUERY_LIMIT}"
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD,req, db)
graph = q.run(query)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
q.close()
@api.route("/game/{db}")
async def api_game(req,resp,*, db):
"""Subgraph intended for use in game engine.
---
get:
summary: Game dataset
description: Returns entire graph for offline use - USE WITH CARE!
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"""
MATCH (n)
WHERE NOT 'Term' IN labels(n) AND
NOT '_Bloom_Scene_' IN labels(n) AND
NOT '_Bloom_Perspective_' IN labels(n)
OPTIONAL MATCH (n)-[r]-(x)
RETURN n,r
"""
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD,req, db)
graph = q.run(query)
# logger.debug(graph)
result = json.loads(graph)
# logger.debug(f"Result: {type(result)}")
path = result['results'][0]['data'][0]['graph']['nodes']
# logger.debug(f"Result graph for calculate_total_content_length: {path}")
result['total_content_length'] = await calculate_total_content_length(path)
json_str = json.dumps(result)
json_size = sys.getsizeof(json_str)
result['total_content_length'] += json_size
resp.media = result
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
q.close()
# @api.route("/ipv4/{db}/{addr}/{length}")
def api_ipv4(req,resp,*, db, addr,length):
"""Subgraph showing all about an IPv4 address.
---
get:
summary: All about IPv4
description: Respond with all feed values required for subgraph showing all about an IPv4 address. given ID and LOD. LOD0 is curated path. LOD1 is path and all nodes within 1 node radius of path. LOD2 is path and all nodes within 2 node radius.
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
- in: path
name: addr
required: true
schema:
type: string
minimum: 1
default: 101.99.128.0
description: The IPV4 starting address e.g. 17 in 101.99.128.0/17
- in: path
name: length
required: true
schema:
type: integer
minimum: 1
default: 17
description: The IPV4 address length e.g. 17 in 101.99.128.0/17
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"\
MATCH (ip4:IPv4 {{inetnum: '{addr}/{length}'}}){chr(10)}\
WITH ip4{chr(10)}\
OPTIONAL MATCH (ip4)-[ro:DELEGATED_TO]-(org:Org){chr(10)}\
WITH ip4, collect(org) as org{chr(10)}\
OPTIONAL MATCH (ip4)-[ra:ORIGINATED_BY]-(asn:ASN){chr(10)}\
WITH ip4, org, collect(ra) AS ra, collect(asn) as asn{chr(10)}\
OPTIONAL MATCH (ip4)-[rc:MAINTAINED_BY|HAS_CONTACT]-(con:Contact){chr(10)}\
WITH ip4, org, ra, asn, collect(rc) AS rc, collect(con) as con{chr(10)}\
RETURN ip4,{chr(10)}\
org AS organisation,{chr(10)}\
ra AS asnEdges,{chr(10)}\
asn AS asn,{chr(10)}\
rc AS contactEdges,{chr(10)}\
con AS contacts{chr(10)}\
"
logger.debug(query)
# logger.debug(req.url.path)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD,req,db)
graph = q.run(query)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
# @api.route("/ipv6/{db}/{addr}/{length}")
def api_ipv6_roa(req,resp,*, db, addr,length):
"""Subgraph showing all about a ROA auth query for IPv6.
---
get:
summary: ROA auth for IPv6
description: Respond with all feed values required for subgraph showing all about a ROA auth query for IPv6. given address
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
- in: path
name: addr
required: true
schema:
type: string
minimum: 1
default: '2407:5600::'
description: The IPv6 address e.g. '2407:5600::'
- in: path
name: length
required: true
schema:
type: string
minimum: 1
default: '32'
description: The IPv6 address length e.g. 32 in 2407:5600::/32
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"\
MATCH (ip6:IPv6 {{inet6num: '{addr}/{length}'}}){chr(10)}\
WITH ip6{chr(10)}\
OPTIONAL MATCH (ip6)-[ORIGINATED_BY]-(asn:ASN){chr(10)}\
WITH ip6, collect(asn) as asnList, collect(asn.aut_num) AS aut_numList{chr(10)}\
OPTIONAL MATCH (roa:ROA){chr(10)}\
WHERE roa.asn IN aut_numList{chr(10)}\
AND roa.lower <= ip6.lower{chr(10)}\
AND roa.upper >= ip6.upper{chr(10)}\
AND ip6.length <= roa.maxLength{chr(10)}\
RETURN ip6, asnList, collect(roa) AS roaList{chr(10)}\
"
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD, req, db)
graph = q.run(query)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
# @api.route("/ipv4/paths/{db}/{addr1}/{length1}/{addr2}/{length2}")
def api_possible_paths(req,resp,*, db, addr1,length1,addr2,length2):
"""Subgraph showing possible paths between two IPv4 adddresses
---
get:
summary: Possible paths between two IPv4 adddresses
description: Respond with all feed values required for subgraph showing all about possible paths between two given IPv4 adddresses
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
- in: path
name: addr1
required: true
schema:
type: string
minimum: 1
default: 202.159.0.0
description: The IPV4 starting address e.g. 202.159.0.0 in 202.159.0.0/24
- in: path
name: length1
required: true
schema:
type: integer
minimum: 1
default: 24
description: The IPV4 address length e.g. 24 in 202.159.0.0/24
- in: path
name: addr2
required: true
schema:
type: string
minimum: 1
default: 104.28.92.0
description: The IPV4 starting address e.g. 104.28.92.0 in 104.28.92.0/24
- in: path
name: length2
required: true
schema:
type: integer
minimum: 1
default: 24
description: The IPV4 address length e.g. 24 in 104.28.92.0/24
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"\
MATCH{chr(10)}\
(i:IPv4 {{inetnum: '{addr1}/{length1}'}}),{chr(10)}\
(n:IPv4 {{inetnum: '{addr2}/{length2}'}}),{chr(10)}\
p = allShortestPaths((i)-[*..5]-(n)){chr(10)}\
RETURN p{chr(10)}\
"
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD, req, db)
graph = q.run(query)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
# @api.route("/asn/{db}/{asn}")
def api_asn(req,resp,*, db, asn):
"""Subgraph showing all about an ASN address.
---
get:
summary: All about ASN
description: Respond with all feed values required for experience showing all about an ASN address. given ID and LOD. LOD0 is curated path. LOD1 is path and all nodes within 1 node radius of path. LOD2 is path and all nodes within 2 node radius.
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
- in: path
name: asn
required: true
schema:
type: string
minimum: 1
default: AS3605
description: The ASN id e.g. AS3605
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f"\
MATCH (asn:ASN {{aut_num: '{asn}'}}){chr(10)}\
WITH asn{chr(10)}\
OPTIONAL MATCH (asn)-[:DELEGATED_TO]-(org:Org){chr(10)}\
WITH asn, collect(org) as org{chr(10)}\
OPTIONAL MATCH (asn)-[]-(set:AS_set){chr(10)}\
WITH asn, org, collect(set) AS set{chr(10)}\
OPTIONAL MATCH (asn)-[r4:ORIGINATED_BY]-(ip4:IPv4){chr(10)}\
WITH asn, org, set, collect(r4) AS r4, collect(ip4) as ip4{chr(10)}\
OPTIONAL MATCH (asn)-[r6:ORIGINATED_BY]-(ip6:IPv6){chr(10)}\
WITH asn, org, set, r4, ip4, collect(r6) AS r6, collect(ip6) AS ip6{chr(10)}\
OPTIONAL MATCH (asn)-[rp:NEIGHBOUR_OF]-(peer:ASN){chr(10)}\
WITH asn, org, set, r4, ip4, r6, ip6, collect(rp) AS rp, collect(peer) AS peer{chr(10)}\
OPTIONAL MATCH (asn)-[rc:MAINTAINED_BY|HAS_CONTACT]-(con:Contact){chr(10)}\
WITH asn, org, set, r4, ip4, r6, ip6, rp, peer, collect(rc) AS rc, collect(con) AS con{chr(10)}\
RETURN asn,{chr(10)}\
org AS organisation,{chr(10)}\
set AS asnSets,{chr(10)}\
con AS contacts,{chr(10)}\
rc AS contactEdges,{chr(10)}\
ip4 AS ip4Prefixes,{chr(10)}\
r4 AS ip4Edges,{chr(10)}\
ip6 AS ip6Prefixes,{chr(10)}\
r6 AS ip6Edges,{chr(10)}\
peer AS asnPeers{chr(10)}\
"
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD, req, db)
graph = q.run(query)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
@api.route("/search/{db}/{query}")
def api_default_freetext_search(req,resp,*, db, query):
"""Subgraph showing free text search results from default index 'defaultFulltextIndex'
---
get:
summary: Search results from defaultFulltextIndex
description: Respond with all .
parameters:
- in: path
name: db
required: true
schema:
type: string
minimum: 1
default: demo
description: The database name
- in: path
name: query
required: true
schema:
type: string
minimum: 1
default: ANZ*
description: The search query e.g. ANZ*
responses:
200:
description: Respond with all feed values required for experience
503:
description: Temporary service issue. Try again later
"""
DATABASE = db
endpoint = f'{NEO4J_API}/{DATABASE}/tx'
query = f'''
CALL db.index.fulltext.queryNodes("defaultFulltextIndex", "{query}") YIELD node
RETURN node
'''
logger.debug(query)
try:
q = GraphQuery(NEO4J_API, NEO4J_USER, NEO4J_PASSWORD, req, db)
graph = q.run(query)
# logger.debug(graph)
resp.media = json.loads(graph)
resp.status_code = 200
except Exception as e:
logger.error(e)
resp.status_code = 503
def neo4j_query(query):
query = query
data = {'statements': [
{'statement': query,
'resultDataContents': ['graph']}]
}
print(data)
r = requests.post(f'{NEO4J_API}/transaction/commit', \
headers = {'Content-type': 'application/json'}, \
json = data, \