-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
utils.py
executable file
·2147 lines (1844 loc) · 75.6 KB
/
utils.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
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
import os
import gc
import re
import ast
import copy
import json
import time
import base64
import select
import shutil
import string
import typing
import logging
import tarfile
import datetime
import requests
import tempfile
import traceback
import subprocess
from lxml import etree
from osgeo import ogr
from PIL import Image
from io import BytesIO, StringIO
from decimal import Decimal
from slugify import slugify
from contextlib import closing
from collections import defaultdict
from math import atan, exp, log, pi, sin, tan, floor
from zipfile import ZipFile, is_zipfile, ZIP_DEFLATED
from requests.packages.urllib3.util.retry import Retry
from django.conf import settings
from django.core.cache import cache
from django.db.models import signals
from django.utils.http import is_safe_url
from django.apps import apps as django_apps
from django.middleware.csrf import get_token
from django.http import HttpResponse
from django.forms.models import model_to_dict
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.core.exceptions import PermissionDenied
from django.core.serializers.json import DjangoJSONEncoder
from django.core.files.storage import default_storage as storage
from django.db import models, connection, transaction
from django.utils.translation import ugettext_lazy as _
from geonode import geoserver, GeoNodeException # noqa
from geonode.compat import ensure_string
from geonode.base.auth import (
extend_token,
get_or_create_token,
get_token_from_auth_header,
get_token_object_from_session)
from urllib.parse import (
urljoin,
unquote,
urlparse,
urlsplit,
urlencode,
parse_qs,
parse_qsl,
ParseResult,
SplitResult
)
MAX_EXTENT = 20037508.34
FULL_ROTATION_DEG = 360.0
HALF_ROTATION_DEG = 180.0
DEFAULT_TITLE = ""
DEFAULT_ABSTRACT = ""
INVALID_PERMISSION_MESSAGE = _("Invalid permission level.")
ALPHABET = f"{string.ascii_uppercase + string.ascii_lowercase + string.digits}-_"
ALPHABET_REVERSE = {c: i for (i, c) in enumerate(ALPHABET)}
BASE = len(ALPHABET)
SIGN_CHARACTER = '$'
SQL_PARAMS_RE = re.compile(r'%\(([\w_\-]+)\)s')
FORWARDED_HEADERS = [
'content-type',
'content-disposition'
]
# explicitly disable resolving XML entities in order to prevent malicious attacks
XML_PARSER: typing.Final = etree.XMLParser(resolve_entities=False)
requests.packages.urllib3.disable_warnings()
signalnames = [
'class_prepared',
'm2m_changed',
'post_delete',
'post_init',
'post_save',
'post_syncdb',
'pre_delete',
'pre_init',
'pre_save']
signals_store = {}
id_none = id(None)
logger = logging.getLogger("geonode.utils")
def unzip_file(upload_file, extension='.shp', tempdir=None):
"""
Unzips a zipfile into a temporary directory and returns the full path of the .shp file inside (if any)
"""
absolute_base_file = None
if tempdir is None:
tempdir = tempfile.mkdtemp(dir=settings.STATIC_ROOT)
if not os.path.isdir(tempdir):
os.makedirs(tempdir)
the_zip = ZipFile(upload_file, allowZip64=True)
the_zip.extractall(tempdir)
for item in the_zip.namelist():
if item.endswith(extension):
absolute_base_file = os.path.join(tempdir, item)
return absolute_base_file
def extract_tarfile(upload_file, extension='.shp', tempdir=None):
"""
Extracts a tarfile into a temporary directory and returns the full path of the .shp file inside (if any)
"""
absolute_base_file = None
if tempdir is None:
tempdir = tempfile.mkdtemp(dir=settings.STATIC_ROOT)
the_tar = tarfile.open(upload_file)
the_tar.extractall(tempdir)
for item in the_tar.getnames():
if item.endswith(extension):
absolute_base_file = os.path.join(tempdir, item)
return absolute_base_file
def get_layer_name(layer):
"""Get the workspace where the input layer belongs"""
_name = layer.name
if _name and ':' in _name:
_name = _name.split(':')[1]
try:
if not _name and layer.alternate:
if ':' in layer.alternate:
_name = layer.alternate.split(':')[1]
else:
_name = layer.alternate
except Exception:
pass
return _name
def get_layer_workspace(layer):
"""Get the workspace where the input layer belongs"""
alternate = None
workspace = None
try:
alternate = layer.alternate
except Exception:
alternate = layer.name
try:
workspace = layer.workspace
except Exception:
workspace = None
if not workspace and alternate and ':' in alternate:
workspace = alternate.split(":")[1]
if not workspace:
default_workspace = getattr(settings, "DEFAULT_WORKSPACE", "geonode")
try:
from geonode.services.enumerations import CASCADED
if layer.remote_service.method == CASCADED:
workspace = getattr(
settings, "CASCADE_WORKSPACE", default_workspace)
else:
raise RuntimeError("Layer is not cascaded")
except AttributeError: # layer does not have a service
workspace = default_workspace
return workspace
def get_headers(request, url, raw_url, allowed_hosts=[]):
cookies = None
csrftoken = None
headers = {}
for _header_key, _header_value in dict(request.headers.copy()).items():
if _header_key.lower() in FORWARDED_HEADERS:
headers[_header_key] = _header_value
if settings.SESSION_COOKIE_NAME in request.COOKIES and is_safe_url(
url=raw_url, allowed_hosts=url.hostname):
cookies = request.META["HTTP_COOKIE"]
for cook in request.COOKIES:
name = str(cook)
value = request.COOKIES.get(name)
if name == 'csrftoken':
csrftoken = value
cook = f"{name}={value}"
cookies = cook if not cookies else (f"{cookies}; {cook}")
csrftoken = get_token(request) if not csrftoken else csrftoken
if csrftoken:
headers['X-Requested-With'] = "XMLHttpRequest"
headers['X-CSRFToken'] = csrftoken
cook = f"csrftoken={csrftoken}"
cookies = cook if not cookies else (f"{cookies}; {cook}")
if cookies:
if 'JSESSIONID' in request.session and request.session['JSESSIONID']:
cookies = f"{cookies}; JSESSIONID={request.session['JSESSIONID']}"
headers['Cookie'] = cookies
if request.method in ("POST", "PUT") and "CONTENT_TYPE" in request.META:
headers["Content-Type"] = request.META["CONTENT_TYPE"]
access_token = None
site_url = urlsplit(settings.SITEURL)
# We want to convert HTTP_AUTH into a Beraer Token only when hitting the local GeoServer
if site_url.hostname in (allowed_hosts + [url.hostname]):
# we give precedence to obtained from Aithorization headers
if 'HTTP_AUTHORIZATION' in request.META:
auth_header = request.META.get(
'HTTP_AUTHORIZATION',
request.META.get('HTTP_AUTHORIZATION2'))
if auth_header:
headers['Authorization'] = auth_header
access_token = get_token_from_auth_header(auth_header, create_if_not_exists=True)
# otherwise we check if a session is active
elif request and request.user.is_authenticated:
access_token = get_token_object_from_session(request.session)
# we extend the token in case the session is active but the token expired
if access_token and access_token.is_expired():
extend_token(access_token)
else:
access_token = get_or_create_token(request.user)
if access_token:
headers['Authorization'] = f'Bearer {access_token}'
pragma = "no-cache"
referer = request.META[
"HTTP_REFERER"] if "HTTP_REFERER" in request.META else \
f"{site_url.scheme}://{site_url.netloc}/"
encoding = request.META["HTTP_ACCEPT_ENCODING"] if "HTTP_ACCEPT_ENCODING" in request.META else "gzip"
headers.update(
{
"Pragma": pragma,
"Referer": referer,
"Accept-encoding": encoding,
})
return (headers, access_token)
def _get_basic_auth_info(request):
"""
grab basic auth info
"""
meth, auth = request.META['HTTP_AUTHORIZATION'].split()
if meth.lower() != 'basic':
raise ValueError
username, password = base64.b64decode(auth.encode()).decode().split(':')
return username, password
def batch_permissions(request):
# TODO
pass
def batch_delete(request):
# TODO
pass
def _split_query(query):
"""
split and strip keywords, preserve space
separated quoted blocks.
"""
qq = query.split(' ')
keywords = []
accum = None
for kw in qq:
if accum is None:
if kw.startswith('"'):
accum = kw[1:]
elif kw:
keywords.append(kw)
else:
accum += f" {kw}"
if kw.endswith('"'):
keywords.append(accum[0:-1])
accum = None
if accum is not None:
keywords.append(accum)
return [kw.strip() for kw in keywords if kw.strip()]
def bbox_to_wkt(x0, x1, y0, y1, srid="4326", include_srid=True):
if srid and str(srid).startswith('EPSG:'):
srid = srid[5:]
if None not in {x0, x1, y0, y1}:
wkt = 'POLYGON(({:f} {:f},{:f} {:f},{:f} {:f},{:f} {:f},{:f} {:f}))'.format(
float(x0), float(y0),
float(x0), float(y1),
float(x1), float(y1),
float(x1), float(y0),
float(x0), float(y0))
if include_srid:
wkt = f'SRID={srid};{wkt}'
else:
wkt = 'POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))'
if include_srid:
wkt = f'SRID=4326;{wkt}'
return wkt
def _v(coord, x, source_srid=4326, target_srid=3857):
if source_srid == 4326 and x and abs(coord) != HALF_ROTATION_DEG:
coord -= (round(coord / FULL_ROTATION_DEG) * FULL_ROTATION_DEG)
if source_srid == 4326 and target_srid != 4326:
if x and float(coord) >= 179.999:
return 179.999
elif x and float(coord) <= -179.999:
return -179.999
if not x and float(coord) >= 89.999:
return 89.999
elif not x and float(coord) <= -89.999:
return -89.999
return coord
def bbox_to_projection(native_bbox, target_srid=4326):
"""
native_bbox must be in the form
('-81.3962935', '-81.3490249', '13.3202891', '13.3859614', 'EPSG:4326')
"""
box = native_bbox[:4]
proj = native_bbox[-1]
minx, maxx, miny, maxy = [float(a) for a in box]
try:
source_srid = int(proj.split(":")[1]) if proj and ':' in proj else int(proj)
except Exception:
source_srid = target_srid
if source_srid != target_srid:
try:
wkt = bbox_to_wkt(_v(minx, x=True, source_srid=source_srid, target_srid=target_srid),
_v(maxx, x=True, source_srid=source_srid, target_srid=target_srid),
_v(miny, x=False, source_srid=source_srid, target_srid=target_srid),
_v(maxy, x=False, source_srid=source_srid, target_srid=target_srid),
srid=source_srid, include_srid=False)
# AF: This causses error with GDAL 3.0.4 due to a breaking change on GDAL
# https://code.djangoproject.com/ticket/30645
import osgeo.gdal
_gdal_ver = osgeo.gdal.__version__.split(".", 2)
from osgeo import ogr
from osgeo.osr import SpatialReference, CoordinateTransformation
g = ogr.Geometry(wkt=wkt)
source = SpatialReference()
source.ImportFromEPSG(source_srid)
dest = SpatialReference()
dest.ImportFromEPSG(target_srid)
if int(_gdal_ver[0]) >= 3 and \
((int(_gdal_ver[1]) == 0 and int(_gdal_ver[2]) >= 4) or int(_gdal_ver[1]) > 0):
source.SetAxisMappingStrategy(0)
dest.SetAxisMappingStrategy(0)
g.Transform(CoordinateTransformation(source, dest))
projected_bbox = [str(x) for x in g.GetEnvelope()]
# Must be in the form : [x0, x1, y0, y1, EPSG:<target_srid>)
return tuple([projected_bbox[0], projected_bbox[1], projected_bbox[2], projected_bbox[3]]) + \
(f"EPSG:{target_srid}",)
except Exception as e:
logger.exception(e)
return native_bbox
def bounds_to_zoom_level(bounds, width, height):
WORLD_DIM = {'height': 256., 'width': 256.}
ZOOM_MAX = 21
def latRad(lat):
_sin = sin(lat * pi / HALF_ROTATION_DEG)
if abs(_sin) != 1.0:
radX2 = log((1.0 + _sin) / (1.0 - _sin)) / 2.0
else:
radX2 = log(1.0) / 2.0
return max(min(radX2, pi), -pi) / 2.0
def zoom(mapPx, worldPx, fraction):
try:
return floor(log(mapPx / worldPx / fraction) / log(2.0))
except Exception:
return 0
ne = [float(bounds[2]), float(bounds[3])]
sw = [float(bounds[0]), float(bounds[1])]
latFraction = (latRad(ne[1]) - latRad(sw[1])) / pi
lngDiff = ne[0] - sw[0]
lngFraction = ((lngDiff + FULL_ROTATION_DEG) if lngDiff < 0 else lngDiff) / FULL_ROTATION_DEG
latZoom = zoom(float(height), WORLD_DIM['height'], latFraction)
lngZoom = zoom(float(width), WORLD_DIM['width'], lngFraction)
# ratio = float(max(width, height)) / float(min(width, height))
# z_offset = 0 if ratio >= 2 else -1
z_offset = 0
zoom = int(max(latZoom, lngZoom) + z_offset)
zoom = 0 if zoom > ZOOM_MAX else zoom
return max(zoom, 0)
def llbbox_to_mercator(llbbox):
minlonlat = forward_mercator([llbbox[0], llbbox[2]])
maxlonlat = forward_mercator([llbbox[1], llbbox[3]])
return [minlonlat[0], minlonlat[1], maxlonlat[0], maxlonlat[1]]
def mercator_to_llbbox(bbox):
minlonlat = inverse_mercator([bbox[0], bbox[2]])
maxlonlat = inverse_mercator([bbox[1], bbox[3]])
return [minlonlat[0], minlonlat[1], maxlonlat[0], maxlonlat[1]]
def forward_mercator(lonlat):
"""
Given geographic coordinates, return a x,y tuple in spherical mercator.
If the lat value is out of range, -inf will be returned as the y value
"""
x = lonlat[0] * MAX_EXTENT / HALF_ROTATION_DEG
try:
# With data sets that only have one point the value of this
# expression becomes negative infinity. In order to continue,
# we wrap this in a try catch block.
n = tan((90 + lonlat[1]) * pi / FULL_ROTATION_DEG)
except ValueError:
n = 0
if n <= 0:
y = float("-inf")
else:
y = log(n) / pi * MAX_EXTENT
return (x, y)
def inverse_mercator(xy):
"""
Given coordinates in spherical mercator, return a lon,lat tuple.
"""
lon = (xy[0] / MAX_EXTENT) * HALF_ROTATION_DEG
lat = (xy[1] / MAX_EXTENT) * HALF_ROTATION_DEG
lat = HALF_ROTATION_DEG / pi * \
(2 * atan(exp(lat * pi / HALF_ROTATION_DEG)) - pi / 2)
return (lon, lat)
def layer_from_viewer_config(map_id, model, layer, source, ordering, save_map=True):
"""
Parse an object out of a parsed layer configuration from a GXP
viewer.
``model`` is the type to instantiate
``layer`` is the parsed dict for the layer
``source`` is the parsed dict for the layer's source
``ordering`` is the index of the layer within the map's layer list
``save_map`` if map should be saved (default: True)
"""
layer_cfg = dict(layer)
for k in ["format", "name", "opacity", "styles", "transparent",
"fixed", "group", "visibility", "source"]:
if k in layer_cfg:
del layer_cfg[k]
layer_cfg["id"] = 1
layer_cfg["wrapDateLine"] = True
layer_cfg["displayOutsideMaxExtent"] = True
source_cfg = dict(source) if source else {}
if source_cfg:
for k in ["url", "projection"]:
if k in source_cfg:
del source_cfg[k]
# We don't want to hardcode 'access_token' into the storage
styles = []
if 'capability' in layer_cfg:
_capability = layer_cfg['capability']
if 'styles' in _capability:
for style in _capability['styles']:
if 'name' in style:
styles.append(style['name'])
if 'legend' in style:
legend = style['legend']
if 'href' in legend:
legend['href'] = re.sub(
r'\&access_token=.*', '', legend['href'])
if not styles and layer.get("styles", None):
for style in layer.get("styles", None):
if 'name' in style:
styles.append(style['name'])
else:
styles.append(style)
_model = model(
map_id=map_id,
stack_order=ordering,
format=layer.get("format", None),
name=layer.get("name", None),
store=layer.get("store", None),
opacity=layer.get("opacity", 1),
styles=styles,
transparent=layer.get("transparent", False),
fixed=layer.get("fixed", False),
group=layer.get('group', None),
visibility=layer.get("visibility", True),
ows_url=source.get("url", None) if source else None,
layer_params=json.dumps(layer_cfg),
source_params=json.dumps(source_cfg)
)
if map_id and save_map:
_model.save()
return _model
class GXPMapBase:
def viewer_json(self, request, *added_layers):
"""
Convert this map to a nested dictionary structure matching the JSON
configuration for GXP Viewers.
The ``added_layers`` parameter list allows a list of extra MapLayer
instances to append to the Map's layer list when generating the
configuration. These are not persisted; if you want to add layers you
should use ``.layer_set.create()``.
"""
user = request.user if request else None
access_token = get_or_create_token(user)
if access_token and not access_token.is_expired():
access_token = access_token.token
if self.id and len(added_layers) == 0:
cfg = cache.get(f"viewer_json_{str(self.id)}_{str(0 if user is None else user.id)}")
if cfg is not None:
return cfg
layers = list(self.layers)
layers.extend(added_layers)
server_lookup = {}
sources = {}
def uniqify(seq):
"""
get a list of unique items from the input sequence.
This relies only on equality tests, so you can use it on most
things. If you have a sequence of hashables, list(set(seq)) is
better.
"""
results = []
for x in seq:
if x not in results:
results.append(x)
return results
configs = [lyr.source_config(access_token) for lyr in layers]
i = 0
for source in uniqify(configs):
while str(i) in sources:
i = i + 1
sources[str(i)] = source
server_lookup[json.dumps(source)] = str(i)
def source_lookup(source):
for k, v in sources.items():
if v == source:
return k
return None
def layer_config(lyr, user=None):
cfg = lyr.layer_config(user=user)
src_cfg = lyr.source_config(access_token)
source = source_lookup(src_cfg)
if source:
cfg["source"] = source
return cfg
source_urls = [source['url']
for source in sources.values() if source and 'url' in source]
if 'geonode.geoserver' in settings.INSTALLED_APPS:
if len(sources.keys()) > 0 and 'source' in settings.MAP_BASELAYERS[0] and \
'url' in settings.MAP_BASELAYERS[0]['source'] and \
not settings.MAP_BASELAYERS[0]['source']['url'] in source_urls:
keys = sorted(sources.keys())
settings.MAP_BASELAYERS[0]['source'][
'title'] = 'Local Geoserver'
sources[str(int(keys[-1]) + 1)
] = settings.MAP_BASELAYERS[0]['source']
def _base_source(source):
base_source = copy.deepcopy(source)
for key in ["id", "baseParams", "title"]:
if base_source and key in base_source:
del base_source[key]
return base_source
for lyr in settings.MAP_BASELAYERS:
if "source" in lyr and _base_source(
lyr["source"]) not in map(
_base_source,
sources.values()):
if len(sources.keys()) > 0:
sources[str(int(max(sources.keys(), key=int)) + 1)
] = lyr["source"]
# adding remote services sources
from geonode.services.models import Service
from geonode.maps.models import Map
if not self.sender or isinstance(self.sender, Map):
index = int(max(sources.keys())) if len(sources.keys()) > 0 else 0
for service in Service.objects.all():
remote_source = {
'url': service.service_url,
'remote': True,
'ptype': service.ptype,
'name': service.name,
'title': f"[R] {service.title}"
}
if remote_source['url'] not in source_urls:
index += 1
sources[index] = remote_source
config = {
'id': self.id,
'about': {
'title': self.title,
'abstract': self.abstract
},
'aboutUrl': '../about',
'defaultSourceType': "gxp_wmscsource",
'sources': sources,
'map': {
'layers': [layer_config(lyr, user=user) for lyr in layers],
'center': [self.center_x, self.center_y],
'projection': self.projection,
'zoom': self.zoom
}
}
if any(layers):
# Mark the last added layer as selected - important for data page
config["map"]["layers"][len(layers) - 1]["selected"] = True
else:
(def_map_config, def_map_layers) = default_map_config(None)
config = def_map_config
config["map"].update(_get_viewer_projection_info(self.projection))
# Create user-specific cache of maplayer config
if self is not None:
cache.set(f"viewer_json_{str(self.id)}_{str(0 if user is None else user.id)}", config)
# Client conversion if needed
from geonode.client.hooks import hookset
config = hookset.viewer_json(config, context={'request': request})
return config
class GXPMap(GXPMapBase):
def __init__(self, sender=None, projection=None, title=None, abstract=None,
center_x=None, center_y=None, zoom=None):
self.id = 0
self.sender = sender
self.projection = projection
self.title = title or DEFAULT_TITLE
self.abstract = abstract or DEFAULT_ABSTRACT
_DEFAULT_MAP_CENTER = forward_mercator(settings.DEFAULT_MAP_CENTER)
self.center_x = center_x if center_x is not None else _DEFAULT_MAP_CENTER[
0]
self.center_y = center_y if center_y is not None else _DEFAULT_MAP_CENTER[
1]
self.zoom = zoom if zoom is not None else settings.DEFAULT_MAP_ZOOM
self.layers = []
class GXPLayerBase:
def source_config(self, access_token):
"""
Generate a dict that can be serialized to a GXP layer source
configuration suitable for loading this layer.
"""
try:
cfg = json.loads(self.source_params)
except Exception:
cfg = dict(ptype="gxp_wmscsource", restUrl="/gs/rest")
if self.ows_url:
'''
This limits the access token we add to only the OGC servers decalred in OGC_SERVER.
Will also override any access_token in the request and replace it with an existing one.
'''
urls = []
for name, server in settings.OGC_SERVER.items():
url = urlsplit(server['PUBLIC_LOCATION'])
urls.append(url.netloc)
my_url = urlsplit(self.ows_url)
if str(access_token) and my_url.netloc in urls:
request_params = parse_qs(my_url.query)
if 'access_token' in request_params:
del request_params['access_token']
# request_params['access_token'] = [access_token]
encoded_params = urlencode(request_params, doseq=True)
parsed_url = SplitResult(
my_url.scheme,
my_url.netloc,
my_url.path,
encoded_params,
my_url.fragment)
cfg["url"] = parsed_url.geturl()
else:
cfg["url"] = self.ows_url
return cfg
def layer_config(self, user=None):
"""
Generate a dict that can be serialized to a GXP layer configuration
suitable for loading this layer.
The "source" property will be left unset; the layer is not aware of the
name assigned to its source plugin. See
geonode.maps.models.Map.viewer_json for an example of
generating a full map configuration.
"""
try:
cfg = json.loads(self.layer_params)
except Exception:
cfg = dict()
if self.format:
cfg['format'] = self.format
if self.name:
cfg["name"] = self.name
if self.opacity:
cfg['opacity'] = self.opacity
if self.styles:
try:
cfg['styles'] = ast.literal_eval(self.styles) \
if isinstance(self.styles, str) else self.styles
except Exception:
pass
if self.transparent:
cfg['transparent'] = True
cfg["fixed"] = self.fixed
if self.group:
cfg["group"] = self.group
cfg["visibility"] = self.visibility
return cfg
class GXPLayer(GXPLayerBase):
'''GXPLayer represents an object to be included in a GXP map.
'''
def __init__(self, name=None, ows_url=None, **kw):
self.format = None
self.name = name
self.opacity = 1.0
self.styles = None
self.transparent = False
self.fixed = False
self.group = None
self.visibility = True
self.wrapDateLine = True
self.displayOutsideMaxExtent = True
self.ows_url = ows_url
self.layer_params = ""
self.source_params = ""
for k in kw:
setattr(self, k, kw[k])
def default_map_config(request):
if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857') == "EPSG:4326":
_DEFAULT_MAP_CENTER = inverse_mercator(settings.DEFAULT_MAP_CENTER)
else:
_DEFAULT_MAP_CENTER = forward_mercator(settings.DEFAULT_MAP_CENTER)
_default_map = GXPMap(
title=DEFAULT_TITLE,
abstract=DEFAULT_ABSTRACT,
projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857'),
center_x=_DEFAULT_MAP_CENTER[0],
center_y=_DEFAULT_MAP_CENTER[1],
zoom=settings.DEFAULT_MAP_ZOOM
)
def _baselayer(lyr, order):
return layer_from_viewer_config(
None,
GXPLayer,
layer=lyr,
source=lyr["source"] if lyr and "source" in lyr else None,
ordering=order
)
DEFAULT_BASE_LAYERS = [
_baselayer(
lyr, idx) for idx, lyr in enumerate(
settings.MAP_BASELAYERS)]
DEFAULT_MAP_CONFIG = _default_map.viewer_json(
request, *DEFAULT_BASE_LAYERS)
return DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS
max_extent = [-MAX_EXTENT, -MAX_EXTENT, MAX_EXTENT, MAX_EXTENT]
_viewer_projection_lookup = {
"EPSG:900913": {
"maxResolution": 156543.03390625,
"units": "m",
"maxExtent": max_extent,
},
"EPSG:3857": {
"maxResolution": 156543.03390625,
"units": "m",
"maxExtent": max_extent,
},
"EPSG:4326": {
"max_resolution": FULL_ROTATION_DEG / 256,
"units": "degrees",
"maxExtent": [-180, -90, 180, 90]
}
}
def _get_viewer_projection_info(srid):
# TODO: Look up projection details in EPSG database
return _viewer_projection_lookup.get(srid, {})
def resolve_object(request, model, query, permission='base.view_resourcebase',
user=None, permission_required=True, permission_msg=None):
"""Resolve an object using the provided query and check the optional
permission. Model views should wrap this function as a shortcut.
query - a dict to use for querying the model
permission - an optional permission to check
permission_required - if False, allow get methods to proceed
permission_msg - optional message to use in 403
"""
user = request.user if request and request.user else user
obj = get_object_or_404(model, **query)
obj_to_check = obj.get_self_resource()
from geonode.groups.models import GroupProfile
from guardian.shortcuts import get_groups_with_perms
groups = get_groups_with_perms(obj_to_check,
attach_perms=True)
if obj_to_check.group and obj_to_check.group not in groups:
groups[obj_to_check.group] = obj_to_check.group
obj_group_managers = []
obj_group_members = []
if groups:
for group in groups:
try:
group_profile = GroupProfile.objects.get(slug=group.name)
managers = group_profile.get_managers()
if managers:
for manager in managers:
if manager not in obj_group_managers and not manager.is_superuser:
obj_group_managers.append(manager)
if group_profile.user_is_member(
user) and user not in obj_group_members:
obj_group_members.append(user)
except GroupProfile.DoesNotExist:
pass
allowed = True
if permission.split('.')[-1] in ['change_layer_data',
'change_layer_style']:
if obj.__class__.__name__ == 'Layer':
obj_to_check = obj
if permission:
if permission_required or request.method != 'GET':
if user in obj_group_managers:
allowed = True
else:
allowed = user.has_perm(
permission,
obj_to_check)
if not allowed:
mesg = permission_msg or _('Permission Denied')
raise PermissionDenied(mesg)
return obj
def json_response(body=None, errors=None, url=None, redirect_to=None, exception=None,
content_type=None, status=None):
"""Create a proper JSON response. If body is provided, this is the response.
If errors is not None, the response is a success/errors json object.
If redirect_to is not None, the response is a success=True, redirect_to object
If the exception is provided, it will be logged. If body is a string, the
exception message will be used as a format option to that string and the
result will be a success=False, errors = body % exception
"""
if isinstance(body, HttpResponse):
return body
if content_type is None:
content_type = "application/json"
if errors:
if isinstance(errors, str):
errors = [errors]
body = {
'success': False,
'errors': errors
}
elif redirect_to:
body = {
'success': True,
'redirect_to': redirect_to
}
elif url:
body = {
'success': True,
'url': url
}
elif exception:
if body is None:
body = f"Unexpected exception {exception}"
else:
body = body % exception
body = {
'success': False,
'errors': [body]
}
elif body:
pass
else:
raise Exception("must call with body, errors or redirect_to")
if status is None:
status = 200
if not isinstance(body, str):
try:
body = json.dumps(body, cls=DjangoJSONEncoder)
except Exception:
body = str(body)
return HttpResponse(body, content_type=content_type, status=status)