-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
models.py
1723 lines (1488 loc) · 56.6 KB
/
models.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
# -*- coding: utf-8 -*-
#########################################################################
#
# 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 re
import glob
import math
import uuid
import logging
import traceback
from django.db import models
from django.conf import settings
from django.core import serializers
from django.utils.html import escape
from django.utils.timezone import now
from django.db.models import Q, signals
from django.contrib.auth.models import Group
from django.core.files.base import ContentFile
from django.contrib.auth import get_user_model
from django.contrib.gis.geos import GEOSGeometry
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.staticfiles.templatetags import staticfiles
from django.core.files.storage import default_storage as storage
from mptt.models import MPTTModel, TreeForeignKey
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from polymorphic.models import PolymorphicModel
from polymorphic.managers import PolymorphicManager
from pinax.ratings.models import OverallRating
from taggit.models import TagBase, ItemBase
from taggit.managers import TaggableManager, _TaggableManager
from treebeard.mp_tree import MP_Node, MP_NodeQuerySet, MP_NodeManager
from geonode.singleton import SingletonModel
from geonode.base.enumerations import (
LINK_TYPES,
ALL_LANGUAGES,
HIERARCHY_LEVELS,
UPDATE_FREQUENCIES,
DEFAULT_SUPPLEMENTAL_INFORMATION)
from geonode.utils import (
add_url_params,
bbox_to_wkt,
forward_mercator)
from geonode.groups.models import GroupProfile
from geonode.security.models import PermissionLevelMixin
from geonode.people.enumerations import ROLE_VALUES
from pyproj import transform, Proj
from urllib.parse import urlparse, urlsplit, urljoin
logger = logging.getLogger(__name__)
class ContactRole(models.Model):
"""
ContactRole is an intermediate model to bind Profiles as Contacts to Resources and apply roles.
"""
resource = models.ForeignKey('ResourceBase', blank=False, null=False, on_delete=models.CASCADE)
contact = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
role = models.CharField(
choices=ROLE_VALUES,
max_length=255,
help_text=_(
'function performed by the responsible '
'party'))
def clean(self):
"""
Make sure there is only one poc and author per resource
"""
if not hasattr(self, 'resource'):
# The ModelForm will already raise a Validation error for a missing resource.
# Re-raising an empty error here ensures the rest of this method isn't
# executed.
raise ValidationError('')
if (self.role == self.resource.poc) or (
self.role == self.resource.metadata_author):
contacts = self.resource.contacts.filter(
contactrole__role=self.role)
if contacts.count() == 1:
# only allow this if we are updating the same contact
if self.contact != contacts.get():
raise ValidationError(
'There can be only one %s for a given resource' %
self.role)
if self.contact is None:
# verify that any unbound contact is only associated to one
# resource
bounds = ContactRole.objects.filter(contact=self.contact).count()
if bounds > 1:
raise ValidationError(
'There can be one and only one resource linked to an unbound contact' %
self.role)
elif bounds == 1:
# verify that if there was one already, it corresponds to this
# instance
if ContactRole.objects.filter(
contact=self.contact).get().id != self.id:
raise ValidationError(
'There can be one and only one resource linked to an unbound contact' %
self.role)
class Meta:
unique_together = (("contact", "resource", "role"),)
class TopicCategory(models.Model):
"""
Metadata about high-level geographic data thematic classification.
It should reflect a list of codes from TC211
See: http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml
<CodeListDictionary gml:id="MD_MD_TopicCategoryCode">
"""
identifier = models.CharField(max_length=255, default='location')
description = models.TextField(default='')
gn_description = models.TextField(
'GeoNode description', default='', null=True)
is_choice = models.BooleanField(default=True)
fa_class = models.CharField(max_length=64, default='fa-times')
def __str__(self):
return self.gn_description
class Meta:
ordering = ("identifier",)
verbose_name_plural = 'Metadata Topic Categories'
class SpatialRepresentationType(models.Model):
"""
Metadata information about the spatial representation type.
It should reflect a list of codes from TC211
See: http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml
<CodeListDictionary gml:id="MD_SpatialRepresentationTypeCode">
"""
identifier = models.CharField(max_length=255, editable=False)
description = models.CharField(max_length=255, editable=False)
gn_description = models.CharField('GeoNode description', max_length=255)
is_choice = models.BooleanField(default=True)
def __str__(self):
return "{0}".format(self.gn_description)
class Meta:
ordering = ("identifier",)
verbose_name_plural = 'Metadata Spatial Representation Types'
class Region(MPTTModel):
code = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=255)
parent = TreeForeignKey(
'self',
null=True,
blank=True,
on_delete=models.CASCADE,
related_name='children')
# Save bbox values in the database.
# This is useful for spatial searches and for generating thumbnail images
# and metadata records.
bbox_x0 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
bbox_x1 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
bbox_y0 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
bbox_y1 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
srid = models.CharField(
max_length=30,
blank=False,
null=False,
default='EPSG:4326')
def __str__(self):
return "{0}".format(self.name)
@property
def bbox(self):
"""BBOX is in the format: [x0,x1,y0,y1]."""
return [
self.bbox_x0,
self.bbox_x1,
self.bbox_y0,
self.bbox_y1,
self.srid]
@property
def bbox_string(self):
"""BBOX is in the format: [x0,y0,x1,y1]."""
return ",".join([str(self.bbox_x0), str(self.bbox_y0),
str(self.bbox_x1), str(self.bbox_y1)])
@property
def geographic_bounding_box(self):
"""BBOX is in the format: [x0,x1,y0,y1]."""
return bbox_to_wkt(
self.bbox_x0,
self.bbox_x1,
self.bbox_y0,
self.bbox_y1,
srid=self.srid)
class Meta:
ordering = ("name",)
verbose_name_plural = 'Metadata Regions'
class MPTTMeta:
order_insertion_by = ['name']
class RestrictionCodeType(models.Model):
"""
Metadata information about the spatial representation type.
It should reflect a list of codes from TC211
See: http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml
<CodeListDictionary gml:id="MD_RestrictionCode">
"""
identifier = models.CharField(max_length=255, editable=False)
description = models.TextField(max_length=255, editable=False)
gn_description = models.TextField('GeoNode description', max_length=255)
is_choice = models.BooleanField(default=True)
def __str__(self):
return "{0}".format(self.gn_description)
class Meta:
ordering = ("identifier",)
verbose_name_plural = 'Metadata Restriction Code Types'
class License(models.Model):
identifier = models.CharField(max_length=255, editable=False)
name = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=20, null=True, blank=True)
description = models.TextField(null=True, blank=True)
url = models.URLField(max_length=2000, null=True, blank=True)
license_text = models.TextField(null=True, blank=True)
def __str__(self):
return "{0}".format(self.name)
@property
def name_long(self):
if self.abbreviation is None or len(self.abbreviation) == 0:
return self.name
else:
return self.name + " (" + self.abbreviation + ")"
@property
def description_bullets(self):
if self.description is None or len(self.description) == 0:
return ""
else:
bullets = []
lines = self.description.split("\n")
for line in lines:
bullets.append("+ " + line)
return bullets
class Meta:
ordering = ("name", )
verbose_name_plural = 'Licenses'
class HierarchicalKeywordQuerySet(MP_NodeQuerySet):
"""QuerySet to automatically create a root node if `depth` not given."""
def create(self, **kwargs):
if 'depth' not in kwargs:
return self.model.add_root(**kwargs)
return super(HierarchicalKeywordQuerySet, self).create(**kwargs)
class HierarchicalKeywordManager(MP_NodeManager):
def get_queryset(self):
return HierarchicalKeywordQuerySet(self.model).order_by('path')
class HierarchicalKeyword(TagBase, MP_Node):
node_order_by = ['name']
objects = HierarchicalKeywordManager()
@classmethod
def dump_bulk_tree(cls, parent=None, keep_ids=True, type=None):
"""Dumps a tree branch to a python data structure."""
qset = cls._get_serializable_model().get_tree(parent)
ret, lnk = [], {}
try:
for pyobj in qset.order_by('name'):
serobj = serializers.serialize('python', [pyobj])[0]
# django's serializer stores the attributes in 'fields'
fields = serobj['fields']
tags_count = 0
try:
tags_count = TaggedContentItem.objects.filter(
content_object__polymorphic_ctype__model=type,
tag=HierarchicalKeyword.objects.get(slug=fields['slug'])).count()
except Exception:
pass
if tags_count > 0:
depth = fields['depth'] or 1
fields['text'] = fields['name']
fields['href'] = fields['slug']
fields['tags'] = [tags_count]
del fields['name']
del fields['slug']
del fields['path']
del fields['numchild']
del fields['depth']
if 'id' in fields:
# this happens immediately after a load_bulk
del fields['id']
newobj = {}
for field in fields:
newobj[field] = fields[field]
if keep_ids:
newobj['id'] = serobj['pk']
if (not parent and depth == 1) or\
(parent and depth == parent.depth):
ret.append(newobj)
else:
parentobj = pyobj.get_parent()
parentser = lnk[parentobj.pk]
if 'nodes' not in parentser:
parentser['nodes'] = []
parentser['nodes'].append(newobj)
lnk[pyobj.pk] = newobj
except Exception:
pass
return ret
class TaggedContentItem(ItemBase):
content_object = models.ForeignKey('ResourceBase', on_delete=models.CASCADE)
tag = models.ForeignKey('HierarchicalKeyword', related_name='keywords', on_delete=models.CASCADE)
# see https://github.com/alex/django-taggit/issues/101
@classmethod
def tags_for(cls, model, instance=None):
if instance is not None:
return cls.tag_model().objects.filter(**{
'%s__content_object' % cls.tag_relname(): instance
})
return cls.tag_model().objects.filter(**{
'%s__content_object__isnull' % cls.tag_relname(): False
}).distinct()
class _HierarchicalTagManager(_TaggableManager):
def add(self, *tags):
str_tags = set([
t
for t in tags
if not isinstance(t, self.through.tag_model())
])
tag_objs = set(tags) - str_tags
# If str_tags has 0 elements Django actually optimizes that to not do a
# query. Malcolm is very smart.
existing = self.through.tag_model().objects.filter(
name__in=str_tags
)
tag_objs.update(existing)
for new_tag in str_tags - set(t.name for t in existing):
if new_tag:
new_tag = escape(new_tag)
tag_objs.add(HierarchicalKeyword.add_root(name=new_tag))
for tag in tag_objs:
try:
self.through.objects.get_or_create(
tag=tag, **self._lookup_kwargs())
except Exception as e:
logger.exception(e)
class Thesaurus(models.Model):
"""
Loadable thesaurus containing keywords in different languages
"""
identifier = models.CharField(
max_length=255,
null=False,
blank=False,
unique=True)
# read from the RDF file
title = models.CharField(max_length=255, null=False, blank=False)
# read from the RDF file
date = models.CharField(max_length=20, default='')
# read from the RDF file
description = models.TextField(max_length=255, default='')
slug = models.CharField(max_length=64, default='')
def __str__(self):
return "{0}".format(self.identifier)
class Meta:
ordering = ("identifier",)
verbose_name_plural = 'Thesauri'
class ThesaurusKeywordLabel(models.Model):
"""
Loadable thesaurus containing keywords in different languages
"""
# read from the RDF file
lang = models.CharField(max_length=3)
# read from the RDF file
label = models.CharField(max_length=255)
# note = models.CharField(max_length=511)
keyword = models.ForeignKey('ThesaurusKeyword', related_name='keyword', on_delete=models.CASCADE)
def __str__(self):
return "{0}".format(self.label)
class Meta:
ordering = ("keyword", "lang")
verbose_name_plural = 'Labels'
unique_together = (("keyword", "lang"),)
class ThesaurusKeyword(models.Model):
"""
Loadable thesaurus containing keywords in different languages
"""
# read from the RDF file
about = models.CharField(max_length=255, null=True, blank=True)
# read from the RDF file
alt_label = models.CharField(
max_length=255,
default='',
null=True,
blank=True)
thesaurus = models.ForeignKey('Thesaurus', related_name='thesaurus', on_delete=models.CASCADE)
def __str__(self):
return "{0}".format(self.alt_label)
@property
def labels(self):
return ThesaurusKeywordLabel.objects.filter(keyword=self)
class Meta:
ordering = ("alt_label",)
verbose_name_plural = 'Thesaurus Keywords'
unique_together = (("thesaurus", "alt_label"),)
class ResourceBaseManager(PolymorphicManager):
def admin_contact(self):
# this assumes there is at least one superuser
superusers = get_user_model().objects.filter(is_superuser=True).order_by('id')
if superusers.count() == 0:
raise RuntimeError(
'GeoNode needs at least one admin/superuser set')
return superusers[0]
def get_queryset(self):
return super(
ResourceBaseManager,
self).get_queryset().non_polymorphic()
def polymorphic_queryset(self):
return super(ResourceBaseManager, self).get_queryset()
class ResourceBase(PolymorphicModel, PermissionLevelMixin, ItemBase):
"""
Base Resource Object loosely based on ISO 19115:2003
"""
VALID_DATE_TYPES = [(x.lower(), _(x))
for x in ['Creation', 'Publication', 'Revision']]
date_help_text = _('reference date for the cited resource')
date_type_help_text = _('identification of when a given event occurred')
edition_help_text = _('version of the cited resource')
abstract_help_text = _(
'brief narrative summary of the content of the resource(s)')
purpose_help_text = _(
'summary of the intentions with which the resource(s) was developed')
maintenance_frequency_help_text = _(
'frequency with which modifications and deletions are made to the data after '
'it is first produced')
keywords_help_text = _(
'commonly used word(s) or formalised word(s) or phrase(s) used to describe the subject '
'(space or comma-separated')
tkeywords_help_text = _(
'formalised word(s) or phrase(s) from a fixed thesaurus used to describe the subject '
'(space or comma-separated')
regions_help_text = _('keyword identifies a location')
restriction_code_type_help_text = _(
'limitation(s) placed upon the access or use of the data.')
constraints_other_help_text = _(
'other restrictions and legal prerequisites for accessing and using the resource or'
' metadata')
license_help_text = _('license of the dataset')
language_help_text = _('language used within the dataset')
category_help_text = _(
'high-level geographic data thematic classification to assist in the grouping and search of '
'available geographic data sets.')
spatial_representation_type_help_text = _(
'method used to represent geographic information in the dataset.')
temporal_extent_start_help_text = _(
'time period covered by the content of the dataset (start)')
temporal_extent_end_help_text = _(
'time period covered by the content of the dataset (end)')
data_quality_statement_help_text = _(
'general explanation of the data producer\'s knowledge about the lineage of a'
' dataset')
doi_help_text = _(
'a DOI will be added by Admin before publication.')
doi = models.TextField(
_('DOI'),
blank=True,
null=True,
help_text=doi_help_text)
# internal fields
uuid = models.CharField(max_length=36)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
null=True,
related_name='owned_resource',
verbose_name=_("Owner"),
on_delete=models.CASCADE)
contacts = models.ManyToManyField(
settings.AUTH_USER_MODEL,
through='ContactRole')
title = models.CharField(_('title'), max_length=255, help_text=_(
'name by which the cited resource is known'))
alternate = models.CharField(max_length=128, null=True, blank=True)
date = models.DateTimeField(
_('date'),
default=now,
help_text=date_help_text)
date_type = models.CharField(
_('date type'),
max_length=255,
choices=VALID_DATE_TYPES,
default='publication',
help_text=date_type_help_text)
edition = models.CharField(
_('edition'),
max_length=255,
blank=True,
null=True,
help_text=edition_help_text)
abstract = models.TextField(
_('abstract'),
max_length=2000,
blank=True,
help_text=abstract_help_text)
purpose = models.TextField(
_('purpose'),
max_length=500,
null=True,
blank=True,
help_text=purpose_help_text)
maintenance_frequency = models.CharField(
_('maintenance frequency'),
max_length=255,
choices=UPDATE_FREQUENCIES,
blank=True,
null=True,
help_text=maintenance_frequency_help_text)
keywords = TaggableManager(
_('keywords'),
through=TaggedContentItem,
blank=True,
help_text=keywords_help_text,
manager=_HierarchicalTagManager)
tkeywords = models.ManyToManyField(
ThesaurusKeyword,
verbose_name=_('keywords'),
null=True,
blank=True,
help_text=tkeywords_help_text)
regions = models.ManyToManyField(
Region,
verbose_name=_('keywords region'),
null=True,
blank=True,
help_text=regions_help_text)
restriction_code_type = models.ForeignKey(
RestrictionCodeType,
verbose_name=_('restrictions'),
help_text=restriction_code_type_help_text,
null=True,
blank=True,
on_delete=models.CASCADE,
limit_choices_to=Q(is_choice=True))
constraints_other = models.TextField(
_('restrictions other'),
blank=True,
null=True,
help_text=constraints_other_help_text)
license = models.ForeignKey(
License,
null=True,
blank=True,
verbose_name=_("License"),
help_text=license_help_text,
on_delete=models.CASCADE)
language = models.CharField(
_('language'),
max_length=3,
choices=ALL_LANGUAGES,
default='eng',
help_text=language_help_text)
category = models.ForeignKey(
TopicCategory,
null=True,
blank=True,
on_delete=models.CASCADE,
limit_choices_to=Q(is_choice=True),
help_text=category_help_text)
spatial_representation_type = models.ForeignKey(
SpatialRepresentationType,
null=True,
blank=True,
on_delete=models.CASCADE,
limit_choices_to=Q(is_choice=True),
verbose_name=_("spatial representation type"),
help_text=spatial_representation_type_help_text)
# Section 5
temporal_extent_start = models.DateTimeField(
_('temporal extent start'),
blank=True,
null=True,
help_text=temporal_extent_start_help_text)
temporal_extent_end = models.DateTimeField(
_('temporal extent end'),
blank=True,
null=True,
help_text=temporal_extent_end_help_text)
supplemental_information = models.TextField(
_('supplemental information'),
max_length=2000,
default=DEFAULT_SUPPLEMENTAL_INFORMATION,
help_text=_('any other descriptive information about the dataset'))
# Section 8
data_quality_statement = models.TextField(
_('data quality statement'),
max_length=2000,
blank=True,
null=True,
help_text=data_quality_statement_help_text)
group = models.ForeignKey(Group, null=True, blank=True, on_delete=models.CASCADE)
# Section 9
# see metadata_author property definition below
# Save bbox values in the database.
# This is useful for spatial searches and for generating thumbnail images
# and metadata records.
bbox_x0 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
bbox_x1 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
bbox_y0 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
bbox_y1 = models.DecimalField(
max_digits=30,
decimal_places=15,
blank=True,
null=True)
srid = models.CharField(
max_length=30,
blank=False,
null=False,
default='EPSG:4326')
# CSW specific fields
csw_typename = models.CharField(
_('CSW typename'),
max_length=32,
default='gmd:MD_Metadata',
null=False)
csw_schema = models.CharField(
_('CSW schema'),
max_length=64,
default='http://www.isotc211.org/2005/gmd',
null=False)
csw_mdsource = models.CharField(
_('CSW source'),
max_length=256,
default='local',
null=False)
csw_insert_date = models.DateTimeField(
_('CSW insert date'), auto_now_add=True, null=True)
csw_type = models.CharField(
_('CSW type'),
max_length=32,
default='dataset',
null=False,
choices=HIERARCHY_LEVELS)
csw_anytext = models.TextField(_('CSW anytext'), null=True, blank=True)
csw_wkt_geometry = models.TextField(
_('CSW WKT geometry'),
null=False,
default='POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))')
# metadata XML specific fields
metadata_uploaded = models.BooleanField(default=False)
metadata_uploaded_preserve = models.BooleanField(_('Metadata uploaded preserve'), default=False)
metadata_xml = models.TextField(
null=True,
default='<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>',
blank=True)
popular_count = models.IntegerField(default=0)
share_count = models.IntegerField(default=0)
featured = models.BooleanField(_("Featured"), default=False, help_text=_(
'Should this resource be advertised in home page?'))
is_published = models.BooleanField(
_("Is Published"),
default=True,
help_text=_('Should this resource be published and searchable?'))
is_approved = models.BooleanField(
_("Approved"),
default=True,
help_text=_('Is this resource validated from a publisher or editor?'))
# fields necessary for the apis
thumbnail_url = models.TextField(_("Thumbnail url"), null=True, blank=True)
detail_url = models.CharField(max_length=255, null=True, blank=True)
rating = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
last_updated = models.DateTimeField(auto_now=True, null=True, blank=True)
# fields controlling security state
dirty_state = models.BooleanField(
_("Dirty State"),
default=False,
help_text=_('Security Rules Are Not Synched with GeoServer!'))
users_geolimits = models.ManyToManyField(
"UserGeoLimit",
related_name="users_geolimits",
null=True,
blank=True)
groups_geolimits = models.ManyToManyField(
"GroupGeoLimit",
related_name="groups_geolimits",
null=True,
blank=True)
def __str__(self):
return "{0}".format(self.title)
def get_upload_session(self):
raise NotImplementedError()
@property
def site_url(self):
return settings.SITEURL
@property
def creator(self):
return self.owner.get_full_name() or self.owner.username
@property
def organizationname(self):
return self.owner.organization
@property
def restriction_code(self):
return self.restriction_code_type.gn_description
@property
def publisher(self):
return self.poc.get_full_name() or self.poc.username
@property
def contributor(self):
return self.metadata_author.get_full_name() or self.metadata_author.username
@property
def topiccategory(self):
return self.category.identifier
@property
def csw_crs(self):
return self.srid
@property
def group_name(self):
if self.group:
return str(self.group).encode("utf-8", "replace")
return None
@property
def bbox(self):
"""BBOX is in the format: [x0,x1,y0,y1]."""
return [
self.bbox_x0,
self.bbox_x1,
self.bbox_y0,
self.bbox_y1,
self.srid]
@property
def ll_bbox(self):
"""BBOX is in the format: [x0,x1,y0,y1]."""
from geonode.utils import bbox_to_projection
llbbox = self.bbox[0:4]
if self.srid and 'EPSG:' in self.srid:
try:
llbbox = bbox_to_projection([float(coord) for coord in llbbox] + [self.srid, ],
target_srid=4326)
except Exception:
pass
return [
llbbox[0], # x0
llbbox[1], # x1
llbbox[2], # y0
llbbox[3], # y1
self.srid]
@property
def ll_bbox_string(self):
"""WGS84 BBOX is in the format: [x0,y0,x1,y1]."""
return ",".join([str(self.ll_bbox[0]), str(self.ll_bbox[2]),
str(self.ll_bbox[1]), str(self.ll_bbox[3])])
@property
def bbox_string(self):
"""BBOX is in the format: [x0,y0,x1,y1]."""
return ",".join([str(self.bbox_x0), str(self.bbox_y0),
str(self.bbox_x1), str(self.bbox_y1)])
@property
def geographic_bounding_box(self):
"""BBOX is in the format: [x0,x1,y0,y1]."""
llbbox = self.ll_bbox[0:4]
return bbox_to_wkt(
llbbox[0], # x0
llbbox[1], # x1
llbbox[2], # y0
llbbox[3], # y1
srid=self.srid)
@property
def license_light(self):
a = []
if not self.license:
return ''
if (not (self.license.name is None)) and (len(self.license.name) > 0):
a.append(self.license.name)
if (not (self.license.url is None)) and (len(self.license.url) > 0):
a.append("(" + self.license.url + ")")
return " ".join(a)
@property
def license_verbose(self):
a = []
if (not (self.license.name_long is None)) and (
len(self.license.name_long) > 0):
a.append(self.license.name_long + ":")
if (not (self.license.description is None)) and (
len(self.license.description) > 0):
a.append(self.license.description)
if (not (self.license.url is None)) and (len(self.license.url) > 0):
a.append("(" + self.license.url + ")")
return " ".join(a)
@property
def metadata_completeness(self):
required_fields = [
'abstract',
'category',
'data_quality_statement',
'date',
'date_type',
'language',
'license',
'regions',
'title']
if self.restriction_code_type == 'otherRestrictions':
required_fields.append('constraints_other')
filled_fields = []
for required_field in required_fields:
field = getattr(self, required_field, None)
if field:
if required_field == 'license':
if field.name == 'Not Specified':
continue
if required_field == 'regions':
if not field.all():
continue
if required_field == 'category':
if not field.identifier:
continue
filled_fields.append(field)
return '{}%'.format(len(filled_fields) * 100 / len(required_fields))
def keyword_list(self):
return [kw.name for kw in self.keywords.all()]
def keyword_slug_list(self):
return [kw.slug for kw in self.keywords.all()]
def region_name_list(self):
return [region.name for region in self.regions.all()]
def spatial_representation_type_string(self):
if hasattr(self.spatial_representation_type, 'identifier'):
return self.spatial_representation_type.identifier
else:
if hasattr(self, 'storeType'):
if self.storeType == 'coverageStore':
return 'grid'
return 'vector'
else:
return None
def set_dirty_state(self):
if not self.dirty_state:
self.dirty_state = True
self.save()
def clear_dirty_state(self):
if self.dirty_state:
self.dirty_state = False
self.save()
@property
def keyword_csv(self):
try:
keywords_qs = self.get_real_instance().keywords.all()
if keywords_qs:
return ','.join([kw.name for kw in keywords_qs])
else:
return ''
except Exception:
return ''