-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
249 lines (228 loc) · 11.2 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
import logging
from django.core.cache import cache
from django.http import Http404, HttpResponse
from django.db import connection
from django.db.utils import IntegrityError
from arches.app.models import models
from arches.app.views.api import APIBase
from arches.app.models.system_settings import settings
from arches.app.models.resource import Resource
from arches.app.models.graph import Graph
from arches.app.utils.response import JSONResponse
from fpan.search.components.rule_filter import RuleFilter
logger = logging.getLogger(__name__)
class MVT(APIBase):
EARTHCIRCUM = 40075016.6856
PIXELSPERTILE = 256
EMPTY_TILE = HttpResponse(b'', content_type="application/x-protobuf")
def get(self, request, nodeid, zoom, x, y):
if hasattr(request.user, "userprofile") is not True:
try:
models.UserProfile.objects.create(user=request.user)
except IntegrityError as e:
logger.warning(e)
raise Http404()
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}_{request.user.username}_{zoom}_{x}_{y}"
tile = cache.get(cache_key)
BUST_RESOURCE_LAYER_CACHE = True
if tile is None or BUST_RESOURCE_LAYER_CACHE is True:
## disable the real postgis spatial query because it was slower (and more picky about the input geometry)
## than just calling another geo query on ES and retrieving ids from
## that. could use another look down the road...
# rules = SiteFilter().get_rules(request.user, str(node.graph_id))
# if rule.type == "geo_filter":
# geom = rules["geometry"]
# # ST_SetSRID({geom}, 4236)
# resid_where = f"ST_Intersects(geom, ST_Transform('{geom}', 3857))"
query_params = {
'nodeid': nodeid,
'zoom': zoom,
'x': x,
'y': y,
}
graphid = str(node.graph_id)
rule = RuleFilter().compile_rules(request.user, graphids=[graphid], single=True)
full_access = False
if rule.type == "no_access":
return self.EMPTY_TILE
elif rule.type == "full_access":
full_access = True
else:
resids = RuleFilter().get_resources_from_rule(rule, ids_only=True)
# if there are not sites this user can view, return and empty tile before
# creating a db connection
if len(resids) == 0:
return self.EMPTY_TILE
# otherwise, add the list of valid ids to query params to be used below
query_params['valid_resids'] = tuple(resids)
with connection.cursor() as cursor:
if int(zoom) <= int(config["clusterMaxZoom"]):
arc = self.EARTHCIRCUM / ((1 << int(zoom)) * self.PIXELSPERTILE)
# add some extra query_params to support clustering
query_params['distance'] = arc * int(config["clusterDistance"])
query_params['min_points'] = int(config["clusterMinPoints"])
if full_access:
# run the basic cluster request and return ALL resources
cursor.execute(
"""WITH clusters(tileid, resourceinstanceid, nodeid, geom, cid)
AS (
SELECT m.*,
ST_ClusterDBSCAN(geom, eps := %(distance)s, minpoints := %(min_points)s) over () AS cid
FROM (
SELECT tileid,
resourceinstanceid,
nodeid,
geom
FROM geojson_geometries
WHERE nodeid = %(nodeid)s
) m
)
SELECT ST_AsMVT(
tile,
%(nodeid)s,
4096,
'geom',
'id'
) FROM (
SELECT resourceinstanceid::text,
row_number() over () as id,
1 as total,
ST_AsMVTGeom(
geom,
TileBBox(%(zoom)s, %(x)s, %(y)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(%(zoom)s, %(x)s, %(y)s, 3857)
) AS geom,
ST_AsGeoJSON(
ST_Extent(geom)
) AS extent
FROM clusters
WHERE cid IS NOT NULL
GROUP BY cid
) as tile;""",
query_params,
)
else:
# if not full access, add a WHERE clause to only return resources in the valid_resids list
cursor.execute(
"""WITH clusters(tileid, resourceinstanceid, nodeid, geom, cid)
AS (
SELECT m.*,
ST_ClusterDBSCAN(geom, eps := %(distance)s, minpoints := %(min_points)s) over () AS cid
FROM (
SELECT tileid,
resourceinstanceid,
nodeid,
geom
FROM geojson_geometries
WHERE nodeid = %(nodeid)s AND resourceinstanceid IN %(valid_resids)s
) m
)
SELECT ST_AsMVT(
tile,
%(nodeid),
4096,
'geom',
'id'
) FROM (
SELECT resourceinstanceid::text,
row_number() over () as id,
1 as total,
ST_AsMVTGeom(
geom,
TileBBox(%(zoom)s, %(x)s, %(y)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(%(zoom)s, %(x)s, %(y)s, 3857)
) AS geom,
ST_AsGeoJSON(
ST_Extent(geom)
) AS extent
FROM clusters
WHERE cid IS NOT NULL
GROUP BY cid
) AS tile;""",
query_params,
)
else:
if full_access is True:
# run the basic request and return ALL resources
cursor.execute(
f"""SELECT ST_AsMVT(tile, %(nodeid)s, 4096, 'geom', 'id') FROM (SELECT tileid,
id,
resourceinstanceid,
nodeid,
ST_AsMVTGeom(
geom,
TileBBox(%(zoom)s, %(x)s, %(y)s, 3857)
) AS geom,
1 AS total
FROM geojson_geometries
WHERE nodeid = %(nodeid)s) AS tile;""",
query_params
)
else:
# add a WHERE clause to only return resources in the valid_resids list
cursor.execute(
f"""SELECT ST_AsMVT(tile, %(nodeid)s, 4096, 'geom', 'id') FROM (SELECT tileid,
id,
resourceinstanceid,
nodeid,
ST_AsMVTGeom(
geom,
TileBBox(%(zoom)s, %(x)s, %(y)s, 3857)
) AS geom,
1 AS total
FROM geojson_geometries
WHERE nodeid = %(nodeid)s AND resourceinstanceid IN %(valid_resids)s) AS tile;""",
query_params
)
tile = bytes(cursor.fetchone()[0])
cache.set(cache_key, tile, settings.TILE_CACHE_TIMEOUT)
if not len(tile):
return self.EMPTY_TILE
return HttpResponse(tile, content_type="application/x-protobuf")
class ResourceIdLookup(APIBase):
def get(self, request):
site_models = [
"Archaeological Site",
"Historic Cemetery",
"Historic Structure"
]
response = {"resources": []}
for g in Graph.objects.filter(name__in=site_models):
resources = Resource.objects.filter(graph_id=g.pk)
for res in resources:
try:
siteid = res.get_node_values("FMSF ID")[0]
except IndexError:
continue
response['resources'].append((g.name, siteid, res.resourceinstanceid))
return JSONResponse(response)