/
api.py
1665 lines (1408 loc) · 72.4 KB
/
api.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 base64 import b64decode
import importlib
import json
import logging
import os
import re
import site
import sys
import uuid
import traceback
from io import StringIO
from oauth2_provider.views import ProtectedResourceView
from pyld.jsonld import compact, frame, from_rdf
from rdflib import RDF
from rdflib.namespace import SKOS, DCTERMS
from revproxy.views import ProxyView
from slugify import slugify
from urllib import parse
from collections import OrderedDict
from django.contrib.auth import authenticate
from django.shortcuts import render
from django.views.generic import View
from django.db import transaction, connection
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.http.request import QueryDict
from django.core import management
from django.core.cache import cache
from django.forms.models import model_to_dict
from django.urls import reverse
from django.utils.translation import get_language, gettext as _
from django.core.files.base import ContentFile
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django_ratelimit.decorators import ratelimit
from arches.app.models import models
from arches.app.models.concept import Concept
from arches.app.models.card import Card as CardProxyModel
from arches.app.models.graph import Graph
from arches.app.models.resource import Resource
from arches.app.models.system_settings import settings
from arches.app.models.tile import Tile as TileProxyModel, TileValidationError
from arches.app.views.tile import TileData as TileView
from arches.app.views.resource import RelatedResourcesView, get_resource_relationship_types
from arches.app.utils.skos import SKOSWriter
from arches.app.utils.response import JSONResponse, JSONErrorResponse
from arches.app.utils.decorators import can_read_concept, group_required
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.data_management.resources.exporter import ResourceExporter
from arches.app.utils.data_management.resources.formats.rdffile import JsonLdReader
from arches.app.utils.data_management.resources.formats.archesfile import ArchesFileReader
from arches.app.utils.permission_backend import (
user_can_read_resource,
user_can_edit_resource,
user_can_delete_resource,
user_can_read_concepts,
user_is_resource_reviewer,
get_restricted_instances,
check_resource_instance_permissions,
get_nodegroups_by_perm,
)
from arches.app.utils.geo_utils import GeoUtils
from arches.app.utils.permission_backend import user_is_resource_editor
from arches.app.search.components.base import SearchFilterFactory
from arches.app.datatypes.datatypes import DataTypeFactory, EDTFDataType
from arches.app.search.search_engine_factory import SearchEngineFactory
logger = logging.getLogger(__name__)
class KibanaProxy(ProxyView):
upstream = settings.KIBANA_URL
def dispatch(self, request, path):
try:
path = f"{settings.KIBANA_CONFIG_BASEPATH}/{path}"
return super(KibanaProxy, self).dispatch(request, path)
except Exception:
logger.exception(_("Failed to dispatch Kibana proxy"))
return JSONResponse(_("KibanaProxy failed"), status=500)
class APIBase(View):
def dispatch(self, request, *args, **kwargs):
try:
get_params = request.GET.copy()
accept = request.META.get("HTTP_ACCEPT")
format = request.GET.get("format", False)
format_values = {
"application/ld+json": "json-ld",
"application/json": "json",
"application/xml": "xml",
}
if not format and accept in format_values:
get_params["format"] = format_values[accept]
for key, value in request.META.items():
if key.startswith("HTTP_X_ARCHES_"):
if key.replace("HTTP_X_ARCHES_", "").lower() not in request.GET:
get_params[key.replace("HTTP_X_ARCHES_", "").lower()] = value
get_params._mutable = False
request.GET = get_params
except Exception:
logger.exception(_("Failed to create API request"))
return super(APIBase, self).dispatch(request, *args, **kwargs)
class GetFrontendI18NData(APIBase):
def get(self, request):
user_language = get_language()
language_file_path = []
language_file_path.append(os.path.join(settings.APP_ROOT, "locale", user_language + ".json"))
for arches_application_name in settings.ARCHES_APPLICATIONS:
application_path = os.path.split(sys.modules[arches_application_name].__spec__.origin)[0]
language_file_path.append(os.path.join(application_path, "locale", user_language + ".json"))
language_file_path.append(os.path.join(settings.ROOT_DIR, "locale", user_language + ".json"))
localized_strings = {}
for lang_file in language_file_path:
try:
localized_strings = json.load(open(lang_file))[user_language] | localized_strings
except FileNotFoundError:
pass
return JSONResponse({
'enabled_languages': {
language_tuple[0]: str(language_tuple[1])
for language_tuple in settings.LANGUAGES
},
'translations': {user_language: localized_strings},
"language": user_language,
})
class GeoJSON(APIBase):
se = SearchEngineFactory().create()
def get_name(self, resource):
graph_function = models.FunctionXGraph.objects.filter(
graph_id=resource.graph_id, function__functiontype="primarydescriptors"
).select_related("function")
if len(graph_function) == 1:
module = graph_function[0].function.get_class_module()()
return module.get_primary_descriptor_from_nodes(self, graph_function[0].config["descriptor_types"]["name"], descriptor="name")
else:
return _("Unnamed Resource")
def get(self, request):
datatype_factory = DataTypeFactory()
set_precision = GeoUtils().set_precision
resourceid = request.GET.get("resourceid", None)
nodeid = request.GET.get("nodeid", None)
nodeids = request.GET.get("nodeids", None)
tileid = request.GET.get("tileid", None)
nodegroups = request.GET.get("nodegroups", [])
precision = request.GET.get("precision", None)
field_name_length = int(request.GET.get("field_name_length", 0))
use_uuid_names = bool(request.GET.get("use_uuid_names", False))
include_primary_name = bool(request.GET.get("include_primary_name", False))
include_geojson_link = bool(request.GET.get("include_geojson_link", False))
use_display_values = bool(request.GET.get("use_display_values", False))
geometry_type = request.GET.get("type", None)
indent = request.GET.get("indent", None)
limit = request.GET.get("limit", None)
page = int(request.GET.get("page", 1))
if limit is not None:
limit = int(limit)
if indent is not None:
indent = int(indent)
if isinstance(nodegroups, str):
nodegroups = nodegroups.split(",")
if hasattr(request.user, "userprofile") is not True:
models.UserProfile.objects.create(user=request.user)
viewable_nodegroups = request.user.userprofile.viewable_nodegroups
nodegroups = [i for i in nodegroups if i in viewable_nodegroups]
nodes = models.Node.objects.filter(datatype="geojson-feature-collection", nodegroup_id__in=viewable_nodegroups)
node_filter = []
if nodeids:
node_filter += nodeids.split(",")
if nodeid:
node_filter.append(nodeid)
nodes = nodes.filter(nodeid__in=node_filter)
nodes = nodes.order_by("sortorder")
features = []
i = 1
property_tiles = models.TileModel.objects.filter(nodegroup_id__in=nodegroups)
property_node_map = {}
property_nodes = models.Node.objects.filter(nodegroup_id__in=nodegroups).order_by("sortorder")
restricted_resource_ids = get_restricted_instances(request.user, self.se)
for node in property_nodes:
property_node_map[str(node.nodeid)] = {"node": node}
if node.fieldname is None or node.fieldname == "":
property_node_map[str(node.nodeid)]["name"] = slugify(node.name, max_length=field_name_length, separator="_")
else:
property_node_map[str(node.nodeid)]["name"] = node.fieldname
tiles = models.TileModel.objects.filter(nodegroup__in=[node.nodegroup for node in nodes])
last_page = None
if resourceid is not None:
tiles = tiles.filter(resourceinstance_id__in=resourceid.split(","))
if tileid is not None:
tiles = tiles.filter(tileid=tileid)
tiles = tiles.order_by("sortorder")
tiles = [tile for tile in tiles if str(tile.resourceinstance_id) not in restricted_resource_ids]
if limit is not None:
start = (page - 1) * limit
end = start + limit
last_page = len(tiles) < end
tiles = tiles[start:end]
for tile in tiles:
data = tile.data
for node in nodes:
try:
for feature_index, feature in enumerate(data[str(node.pk)]["features"]):
if geometry_type is None or geometry_type == feature["geometry"]["type"]:
if len(nodegroups) > 0:
for pt in property_tiles.filter(resourceinstance_id=tile.resourceinstance_id).order_by("sortorder"):
for key in pt.data:
field_name = key if use_uuid_names else property_node_map[key]["name"]
if pt.data[key] is not None:
if use_display_values:
property_node = property_node_map[key]["node"]
datatype = datatype_factory.get_instance(property_node.datatype)
value = datatype.get_display_value(pt, property_node)
else:
value = pt.data[key]
try:
feature["properties"][field_name].append(value)
except KeyError:
feature["properties"][field_name] = value
except AttributeError:
feature["properties"][field_name] = [feature["properties"][field_name], value]
if include_primary_name:
feature["properties"]["primary_name"] = self.get_name(tile.resourceinstance)
feature["properties"]["resourceinstanceid"] = tile.resourceinstance_id
feature["properties"]["tileid"] = tile.pk
try:
feature["properties"].pop("nodeId")
except KeyError:
pass
feature["properties"]["nodeid"] = node.pk
if include_geojson_link:
feature["properties"]["geojson"] = "%s?tileid=%s&nodeid=%s" % (reverse("geojson"), tile.pk, node.pk)
feature["id"] = i
if precision is not None:
coordinates = set_precision(feature["geometry"]["coordinates"], precision)
feature["geometry"]["coordinates"] = coordinates
i += 1
features.append(feature)
except KeyError:
pass
except TypeError:
pass
feature_collection = {"type": "FeatureCollection", "features": features}
if last_page is not None:
feature_collection["_page"] = page
feature_collection["_lastPage"] = last_page
response = JSONResponse(feature_collection, indent=indent)
return response
class MVT(APIBase):
EARTHCIRCUM = 40075016.6856
PIXELSPERTILE = 256
def get(self, request, nodeid, zoom, x, y):
if hasattr(request.user, "userprofile") is not True:
models.UserProfile.objects.create(user=request.user)
viewable_nodegroups = request.user.userprofile.viewable_nodegroups
try:
node = models.Node.objects.get(nodeid=nodeid, nodegroup_id__in=viewable_nodegroups)
except models.Node.DoesNotExist:
raise Http404()
config = node.config
cache_key = f"mvt_{nodeid}_{zoom}_{x}_{y}"
tile = cache.get(cache_key)
if tile is None:
resource_ids = get_restricted_instances(request.user, allresources=True)
if len(resource_ids) == 0:
resource_ids.append("10000000-0000-0000-0000-000000000001") # This must have a uuid that will never be a resource id.
resource_ids = tuple(resource_ids)
with connection.cursor() as cursor:
if int(zoom) <= int(config["clusterMaxZoom"]):
arc = self.EARTHCIRCUM / ((1 << int(zoom)) * self.PIXELSPERTILE)
distance = arc * float(config["clusterDistance"])
min_points = int(config["clusterMinPoints"])
distance = settings.CLUSTER_DISTANCE_MAX if distance > settings.CLUSTER_DISTANCE_MAX else distance
cursor.execute(
"""WITH clusters(tileid, resourceinstanceid, nodeid, geom, cid)
AS (
SELECT m.*,
ST_ClusterDBSCAN(geom, eps := %s, minpoints := %s) over () AS cid
FROM (
SELECT tileid,
resourceinstanceid,
nodeid,
geom
FROM geojson_geometries
WHERE nodeid = %s and resourceinstanceid not in %s
) m
)
SELECT ST_AsMVT(
tile,
%s,
4096,
'geom',
'id'
) FROM (
SELECT resourceinstanceid::text,
row_number() over () as id,
1 as total,
ST_AsMVTGeom(
geom,
TileBBox(%s, %s, %s, 3857)
) AS geom,
'' AS extent
FROM clusters
WHERE cid is NULL
UNION
SELECT NULL as resourceinstanceid,
row_number() over () as id,
count(*) as total,
ST_AsMVTGeom(
ST_Centroid(
ST_Collect(geom)
),
TileBBox(%s, %s, %s, 3857)
) AS geom,
ST_AsGeoJSON(
ST_Extent(geom)
) AS extent
FROM clusters
WHERE cid IS NOT NULL
GROUP BY cid
) as tile;""",
[distance, min_points, nodeid, resource_ids, nodeid, zoom, x, y, zoom, x, y],
)
else:
cursor.execute(
"""SELECT ST_AsMVT(tile, %s, 4096, 'geom', 'id') FROM (SELECT tileid,
id,
resourceinstanceid,
nodeid,
ST_AsMVTGeom(
geom,
TileBBox(%s, %s, %s, 3857)
) AS geom,
1 AS total
FROM geojson_geometries
WHERE nodeid = %s and resourceinstanceid not in %s) AS tile;""",
[nodeid, zoom, x, y, nodeid, resource_ids],
)
tile = bytes(cursor.fetchone()[0])
cache.set(cache_key, tile, settings.TILE_CACHE_TIMEOUT)
if not len(tile):
raise Http404()
return HttpResponse(tile, content_type="application/x-protobuf")
@method_decorator(csrf_exempt, name="dispatch")
class Graphs(APIBase):
action = None
def get(self, request, graph_id=None):
cards_querystring = request.GET.get("cards", None)
exclusions_querystring = request.GET.get("exclude", None)
if cards_querystring == "false":
get_cards = False
else:
get_cards = True
if exclusions_querystring is not None:
exclusions = list(map(str.strip, exclusions_querystring.split(",")))
else:
exclusions = []
perm = "read_nodegroup"
user = request.user
if graph_id and not self.action:
graph = Graph.objects.get(graphid=graph_id)
graph = JSONSerializer().serializeToPython(graph, sort_keys=False, exclude=["is_editable", "functions"] + exclusions)
if get_cards:
datatypes = models.DDataType.objects.all()
cards = CardProxyModel.objects.filter(graph_id=graph_id).order_by("sortorder")
permitted_cards = []
for card in cards:
if user.has_perm(perm, card.nodegroup):
card.filter_by_perm(user, perm)
permitted_cards.append(card)
cardwidgets = [
widget
for widgets in [card.cardxnodexwidget_set.order_by("sortorder").all() for card in permitted_cards]
for widget in widgets
]
permitted_cards = JSONSerializer().serializeToPython(permitted_cards, sort_keys=False, exclude=["is_editable"])
return JSONResponse({"datatypes": datatypes, "cards": permitted_cards, "graph": graph, "cardwidgets": cardwidgets})
else:
return JSONResponse({"graph": graph})
elif self.action == "get_graph_models":
graphs = models.GraphModel.objects.all()
return JSONResponse(JSONSerializer().serializeToPython(graphs))
@method_decorator(csrf_exempt, name="dispatch")
class Resources(APIBase):
# context = [{
# "@context": {
# "id": "@id",
# "type": "@type",
# "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
# "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
# "crm": "http://www.cidoc-crm.org/cidoc-crm/",
# "la": "https://linked.art/ns/terms/",
# "Right": "crm:E30_Right",
# "LinguisticObject": "crm:E33_Linguistic_Object",
# "Name": "la:Name",
# "Identifier": "crm:E42_Identifier",
# "Language": "crm:E56_Language",
# "Type": "crm:E55_Type",
# "label": "rdfs:label",
# "value": "rdf:value",
# "classified_as": "crm:P2_has_type",
# "referred_to_by": "crm:P67i_is_referred_to_by",
# "language": "crm:P72_has_language",
# "includes": "crm:P106_is_composed_of",
# "identified_by": "crm:P1_is_identified_by"
# }
# },{
# "@context": "https://linked.art/ns/v1/linked-art.json"
# }]
def get(self, request, resourceid=None, slug=None, graphid=None):
if not user_can_read_resource(user=request.user, resourceid=resourceid):
return JSONResponse(status=403)
allowed_formats = ["json", "json-ld", "arches-json"]
format = request.GET.get("format", "json-ld")
hide_hidden_nodes = bool(request.GET.get("hidden", "true").lower() == "false")
user = request.user
perm = "read_nodegroup"
if format not in allowed_formats:
return JSONResponse(status=406, reason="incorrect format specified, only %s formats allowed" % allowed_formats)
indent = request.GET.get("indent")
if indent and str.isdigit(indent):
indent = int(indent)
else:
indent = None
if resourceid:
if format == "json":
resource = Resource.objects.get(pk=resourceid)
version = request.GET.get("v", None)
compact = bool(request.GET.get("compact", "true").lower() == "true") # default True
hide_empty_nodes = bool(request.GET.get("hide_empty_nodes", "false").lower() == "true") # default False
if version == "beta":
out = resource.to_json(
compact=compact,
hide_empty_nodes=hide_empty_nodes,
user=user,
perm=perm,
version=version,
hide_hidden_nodes=hide_hidden_nodes,
)
else:
out = {
"resource": resource.to_json(
compact=compact,
hide_empty_nodes=hide_empty_nodes,
user=user,
perm=perm,
version=version,
hide_hidden_nodes=hide_hidden_nodes,
),
"displaydescription": resource.displaydescription(),
"displayname": resource.displayname(),
"graph_id": resource.graph_id,
"legacyid": resource.legacyid,
"map_popup": resource.map_popup(),
"resourceinstanceid": resource.resourceinstanceid,
}
elif format == "arches-json":
out = Resource.objects.get(pk=resourceid)
include_tiles = bool(request.GET.get("includetiles", "true").lower() == "true") # default True
if include_tiles:
out.load_tiles(user, perm)
elif format == "json-ld":
try:
models.ResourceInstance.objects.get(pk=resourceid) # check for existance
exporter = ResourceExporter(format=format)
output = exporter.writer.write_resources(resourceinstanceids=[resourceid], indent=indent, user=request.user)
out = output[0]["outputfile"].getvalue()
except models.ResourceInstance.DoesNotExist:
logger.error(_("The specified resource '{0}' does not exist. JSON-LD export failed.".format(resourceid)))
return JSONResponse(status=404)
else:
#
# The following commented code would be what you would use if you wanted to use the rdflib module,
# the problem with using this is that items in the "ldp:contains" array don't maintain a consistent order
#
# archesproject = Namespace(settings.ARCHES_NAMESPACE_FOR_DATA_EXPORT)
# ldp = Namespace('https://www.w3.org/ns/ldp/')
# g = Graph()
# g.bind('archesproject', archesproject, False)
# g.add((archesproject['resources'], RDF.type, ldp['BasicContainer']))
# base_url = "%s%s" % (settings.ARCHES_NAMESPACE_FOR_DATA_EXPORT, reverse('resources',args=['']).lstrip('/'))
# for resourceid in list(Resource.objects.values_list('pk', flat=True).order_by('pk')[:10]):
# g.add((archesproject['resources'], ldp['contains'], URIRef("%s%s") % (base_url, resourceid) ))
# value = g.serialize(format='nt')
# out = from_rdf(str(value), options={format:'application/nquads'})
# framing = {
# "@omitDefault": True
# }
# out = frame(out, framing)
# context = {
# "@context": {
# 'ldp': 'https://www.w3.org/ns/ldp/',
# 'arches': settings.ARCHES_NAMESPACE_FOR_DATA_EXPORT
# }
# }
# out = compact(out, context, options={'skipExpansion':False, 'compactArrays': False})
page_size = settings.API_MAX_PAGE_SIZE
try:
page = int(request.GET.get("page", None))
except Exception:
page = 1
start = (page - 1) * page_size
end = start + page_size
base_url = "%s%s" % (settings.ARCHES_NAMESPACE_FOR_DATA_EXPORT, reverse("resources", args=[""]).lstrip("/"))
out = {
"@context": "https://www.w3.org/ns/ldp/",
"@id": "",
"@type": "ldp:BasicContainer",
# Here we actually mean the name
# "label": str(model.name),
"ldp:contains": [
"%s%s" % (base_url, resourceid)
for resourceid in list(
Resource.objects.values_list("pk", flat=True)
.exclude(pk=settings.SYSTEM_SETTINGS_RESOURCE_ID)
.order_by("pk")[start:end]
)
],
}
return JSONResponse(out, indent=indent)
def put(self, request, resourceid, slug=None, graphid=None):
allowed_formats = ["arches-json", "json-ld"]
indent = request.GET.get("indent", None)
format = request.GET.get("format", "json-ld")
if format not in allowed_formats:
return JSONResponse(status=406, reason="incorrect format specified, only %s formats allowed" % allowed_formats)
if format == "json-ld" and slug is None and graphid is None:
return JSONResponse({"error": "Need to supply either a graph id or slug in the request url. See the API reference in the developer documentation at https://arches.readthedocs.io for more details"}, status=400)
if not user_can_edit_resource(user=request.user, resourceid=resourceid):
return JSONResponse(status=403)
else:
with transaction.atomic():
try:
if format == "json-ld":
data = JSONDeserializer().deserialize(request.body)
reader = JsonLdReader()
if slug is not None:
graphid = models.GraphModel.objects.get(slug=slug).pk
reader.read_resource(data, resourceid=resourceid, graphid=graphid)
if reader.errors:
response = []
for value in reader.errors.values():
response.append(value.message)
return JSONResponse({"error": response}, indent=indent, status=400)
else:
response = []
for resource in reader.resources:
with transaction.atomic():
try:
# DELETE
resource_instance = Resource.objects.get(pk=resource.pk)
resource_instance.delete()
except models.ResourceInstance.DoesNotExist:
pass
resource.save(request=request)
response.append(JSONDeserializer().deserialize(self.get(request, resource.resourceinstanceid).content))
return JSONResponse(response, indent=indent, status=201)
elif format == "arches-json":
reader = ArchesFileReader()
archesresource = JSONDeserializer().deserialize(request.body)
# IF a resource id is supplied in the url it should match the resource ids in the body of the request.
if resourceid != archesresource["resourceinstanceid"]:
return JSONResponse(
{"error": "Resource id in the URI does not match the resourceinstanceid supplied in the document"},
indent=indent,
status=400,
)
# Resource id's in the request body take precedence over the id supplied in the url.
resource = {
"resourceinstance": {
"graph_id": archesresource["graph_id"],
"resourceinstanceid": archesresource["resourceinstanceid"],
"legacyid": archesresource["legacyid"],
},
"tiles": archesresource["tiles"],
}
reader.import_business_data({"resources": [resource]})
if reader.errors:
response = []
for value in reader.errors.values():
response.append(value.message)
return JSONResponse({"error": response}, indent=indent, status=400)
else:
response = []
response.append(JSONDeserializer().deserialize(self.get(request, archesresource["resourceinstanceid"]).content))
return JSONResponse(response, indent=indent, status=201)
except models.ResourceInstance.DoesNotExist:
return JSONResponse(status=404)
except Exception as e:
return JSONResponse({"error": "resource data could not be saved"}, status=500, reason=e)
def post(self, request, resourceid=None, slug=None, graphid=None):
allowed_formats = ["arches-json", "json-ld"]
indent = request.POST.get("indent", None)
format = request.GET.get("format", "json-ld")
if format not in allowed_formats:
return JSONResponse(status=406, reason="incorrect format specified, only %s formats allowed" % allowed_formats)
if format == "json-ld" and slug is None and graphid is None:
return JSONResponse({"error": "Need to supply either a graph id or slug in the request url. See the API reference in the developer documentation at https://arches.readthedocs.io for more details"}, status=400)
try:
if user_can_edit_resource(user=request.user, resourceid=resourceid):
if format == "json-ld":
data = JSONDeserializer().deserialize(request.body)
reader = JsonLdReader()
if slug is not None:
graphid = models.GraphModel.objects.get(slug=slug).pk
reader.read_resource(data, graphid=graphid)
if reader.errors:
response = []
for value in reader.errors.values():
response.append(value.message)
return JSONResponse({"error": response}, indent=indent, status=400)
else:
response = []
for resource in reader.resources:
with transaction.atomic():
resource.save(request=request)
response.append(JSONDeserializer().deserialize(self.get(request, resource.resourceinstanceid).content))
return JSONResponse(response, indent=indent, status=201)
elif format == "arches-json":
reader = ArchesFileReader()
archesresource = JSONDeserializer().deserialize(request.body)
nascent_resourceinstanceid = str(uuid.uuid4())
resource = {
"resourceinstance": {
"graph_id": archesresource["graph_id"],
"resourceinstanceid": nascent_resourceinstanceid,
"legacyid": archesresource["legacyid"],
},
"tiles": archesresource["tiles"],
}
reader.import_business_data({"resources": [resource]})
if reader.errors:
response = []
for value in reader.errors.values():
response.append(value.message)
return JSONResponse({"error": response}, indent=indent, status=400)
else:
response = []
response.append(JSONDeserializer().deserialize(self.get(request, nascent_resourceinstanceid).content))
return JSONResponse(response, indent=indent, status=201)
else:
return JSONResponse(status=403)
except Exception as e:
if settings.DEBUG is True:
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted = traceback.format_exception(exc_type, exc_value, exc_traceback)
if len(formatted):
for message in formatted:
print(message)
return JSONResponse({"error": "resource data could not be saved: %s" % e}, status=500, reason=e)
def delete(self, request, resourceid, slug=None, graphid=None):
if user_can_edit_resource(user=request.user, resourceid=resourceid) and user_can_delete_resource(
user=request.user, resourceid=resourceid
):
try:
resource_instance = Resource.objects.get(pk=resourceid)
resource_instance.delete()
except models.ResourceInstance.DoesNotExist:
return JSONResponse(status=404)
else:
return JSONResponse(status=500)
return JSONResponse(status=200)
@method_decorator(csrf_exempt, name="dispatch")
class Concepts(APIBase):
def get(self, request, conceptid=None):
if user_can_read_concepts(user=request.user):
allowed_formats = ["json", "json-ld"]
format = request.GET.get("format", "json-ld")
if format not in allowed_formats:
return JSONResponse(status=406, reason="incorrect format specified, only %s formats allowed" % allowed_formats)
include_subconcepts = request.GET.get("includesubconcepts", "true") == "true"
include_parentconcepts = request.GET.get("includeparentconcepts", "true") == "true"
include_relatedconcepts = request.GET.get("includerelatedconcepts", "true") == "true"
depth_limit = request.GET.get("depthlimit", None)
lang = request.GET.get("lang", settings.LANGUAGE_CODE)
try:
indent = int(request.GET.get("indent", None))
except Exception:
indent = None
if conceptid:
try:
ret = []
concept_graph = Concept().get(
id=conceptid,
include_subconcepts=include_subconcepts,
include_parentconcepts=include_parentconcepts,
include_relatedconcepts=include_relatedconcepts,
depth_limit=depth_limit,
up_depth_limit=None,
lang=lang,
)
ret.append(concept_graph)
except models.Concept.DoesNotExist:
return JSONResponse(status=404)
except Exception as e:
return JSONResponse(status=500, reason=e)
else:
return JSONResponse(status=500)
else:
return JSONResponse(status=500)
if format == "json-ld":
try:
skos = SKOSWriter()
value = skos.write(ret, format="nt")
js = from_rdf(value.decode("utf-8"), options={format: "application/nquads"})
context = [{"@context": {"skos": SKOS, "dcterms": DCTERMS, "rdf": str(RDF)}}, {"@context": settings.RDM_JSONLD_CONTEXT}]
ret = compact(js, context)
except Exception as e:
return JSONResponse(status=500, reason=e)
return JSONResponse(ret, indent=indent)
class Card(APIBase):
def get(self, request, resourceid):
try:
resource_instance = Resource.objects.get(pk=resourceid)
graph = resource_instance.graph
except Resource.DoesNotExist:
graph = models.GraphModel.objects.get(pk=resourceid)
resourceid = None
resource_instance = None
pass
nodegroups = []
editable_nodegroups = []
nodes = graph.node_set.all().select_related("nodegroup")
for node in nodes:
if node.is_collector:
added = False
if request.user.has_perm("write_nodegroup", node.nodegroup):
editable_nodegroups.append(node.nodegroup)
nodegroups.append(node.nodegroup)
added = True
if not added and request.user.has_perm("read_nodegroup", node.nodegroup):
nodegroups.append(node.nodegroup)
user_is_reviewer = user_is_resource_reviewer(request.user)
if resource_instance is None:
tiles = []
displayname = _("New Resource")
else:
displayname = resource_instance.displayname()
if displayname == "undefined":
displayname = _("Unnamed Resource")
if str(resource_instance.graph_id) == settings.SYSTEM_SETTINGS_RESOURCE_MODEL_ID:
displayname = _("System Settings")
tiles = resource_instance.tilemodel_set.order_by("sortorder").filter(nodegroup__in=nodegroups)
provisionaltiles = []
for tile in tiles:
append_tile = True
isfullyprovisional = False
if tile.provisionaledits is not None:
if len(list(tile.provisionaledits.keys())) > 0:
if len(tile.data) == 0:
isfullyprovisional = True
if user_is_reviewer is False:
if str(request.user.id) in tile.provisionaledits:
tile.provisionaledits = {str(request.user.id): tile.provisionaledits[str(request.user.id)]}
tile.data = tile.provisionaledits[str(request.user.id)]["value"]
else:
if isfullyprovisional is True:
# if the tile IS fully provisional and the current user is not the owner,
# we don't send that tile back to the client.
append_tile = False
else:
# if the tile has authoritaive data and the current user is not the owner,
# we don't send the provisional data of other users back to the client.
tile.provisionaledits = None
if append_tile is True:
provisionaltiles.append(tile)
tiles = provisionaltiles
serialized_graph = None
if graph.publication:
published_graph = graph.get_published_graph()
serialized_graph = published_graph.serialized_graph
if serialized_graph:
serialized_cards = serialized_graph["cards"]
cardwidgets = [
widget
for widget in models.CardXNodeXWidget.objects.filter(
pk__in=[widget_dict["id"] for widget_dict in serialized_graph["widgets"]]
)
]
else:
cards = graph.cardmodel_set.order_by("sortorder").filter(nodegroup__in=nodegroups).prefetch_related("cardxnodexwidget_set")
serialized_cards = JSONSerializer().serializeToPython(cards)
cardwidgets = [widget for widget in [card.cardxnodexwidget_set.order_by("sortorder").all() for card in cards]]
editable_nodegroup_ids = [str(nodegroup.pk) for nodegroup in editable_nodegroups]
for card in serialized_cards:
card["is_writable"] = False
if str(card["nodegroup_id"]) in editable_nodegroup_ids:
card["is_writable"] = True
context = {
"resourceid": resourceid,
"displayname": displayname,
"tiles": tiles,
"cards": serialized_cards,
"nodegroups": nodegroups,
"nodes": nodes.filter(nodegroup__in=nodegroups),
"cardwidgets": cardwidgets,
"datatypes": models.DDataType.objects.all(),
"userisreviewer": user_is_reviewer,
"widgets": models.Widget.objects.all(),
"card_components": models.CardComponent.objects.all(),
}
return JSONResponse(context, indent=4)
class Plugins(View):
def get(self, request, plugin_id=None):
if plugin_id:
plugins = models.Plugin.objects.filter(pk=plugin_id)
else:
plugins = models.Plugin.objects.all()
plugins = [plugin for plugin in plugins if self.request.user.has_perm("view_plugin", plugin)]
return JSONResponse(plugins)
class SearchExport(View):
@method_decorator(ratelimit(key="header:http-authorization", rate=settings.RATE_LIMIT, block=False))
def get(self, request):
from arches.app.search.search_export import SearchResultsExporter # avoids circular import
total = int(request.GET.get("total", 0))
download_limit = settings.SEARCH_EXPORT_IMMEDIATE_DOWNLOAD_THRESHOLD
format = request.GET.get("format", "tilecsv")
report_link = request.GET.get("reportlink", False)
if "HTTP_AUTHORIZATION" in request.META and not request.get("limited", False):
request_auth = request.META.get("HTTP_AUTHORIZATION").split()
if request_auth[0].lower() == "basic":
user_cred = b64decode(request_auth[1]).decode().split(":")
user = authenticate(username=user_cred[0], password=user_cred[1])
if user is not None:
request.user = user
exporter = SearchResultsExporter(search_request=request)
export_files, export_info = exporter.export(format, report_link)
if format == "geojson" and total <= download_limit:
if settings.EXPORT_DATA_FIELDS_IN_CARD_ORDER:
response = JSONResponse(export_files, sort_keys=False)
else:
response = JSONResponse(export_files)
return response
return JSONResponse(status=404)
class SearchComponentData(APIBase):
def get(self, request, componentname):
search_filter_factory = SearchFilterFactory(request)
search_filter = search_filter_factory.get_filter(componentname)
if search_filter:
return JSONResponse(search_filter.view_data())
return JSONResponse(status=404)
@method_decorator(csrf_exempt, name="dispatch")
class Images(APIBase):
# meant to handle uploading of full sized images from a mobile client
def post(self, request):
tileid = request.POST.get("tileid")
fileid = request.POST.get("file_id")
nodeid = request.POST.get("nodeid")
file_name = request.POST.get("file_name", "temp.jpg")
file_data = request.FILES.get("data")
try:
image_file, file_created = models.File.objects.get_or_create(pk=fileid)
image_file.path.save(file_name, ContentFile(file_data.read()))
tile = TileProxyModel.objects.get(pk=tileid)
tile_data = tile.get_tile_data(request.user.pk)
for image in tile_data[nodeid]:
if image["file_id"] == fileid:
image["url"] = image_file.path.url
image["size"] = image_file.path.size
# I don't really want to run all the code TileProxyModel.save(),
# so I just call it's super class
super(TileProxyModel, tile).save()
tile.index()
# to use base64 use the below code
# import base64
# with open("foo.jpg", "w+b") as f:
# f.write(base64.b64decode(request.POST.get('data')))
except Exception as e:
return JSONResponse(status=500)
return JSONResponse()
class IIIFManifest(APIBase):
def get(self, request):
query = request.GET.get("query", None)
start = int(request.GET.get("start", 0))
limit = request.GET.get("limit", None)
more = False
manifests = models.IIIFManifest.objects.all()
if query is not None:
manifests = manifests.filter(Q(label__icontains=query) | Q(description__icontains=query))
count = manifests.count()
if limit is not None:
manifests = manifests[start : start + int(limit)]
more = start + int(limit) < count