-
Notifications
You must be signed in to change notification settings - Fork 31
/
_stac.py
1362 lines (1164 loc) · 43.5 KB
/
_stac.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
import json
import logging
import uuid
from datetime import datetime, timedelta
from datetime import time as dt_time
from functools import partial
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import flask
import pystac
from datacube.model import Dataset, Range
from datacube.utils import DocReader, parse_time
from dateutil.tz import tz
from eodatasets3 import serialise
from eodatasets3 import stac as eo3stac
from eodatasets3.model import AccessoryDoc, DatasetDoc, MeasurementDoc, ProductDoc
from eodatasets3.properties import Eo3Dict
from eodatasets3.utils import is_doc_eo3
from flask import abort, request
from pystac import Catalog, Collection, Extent, ItemCollection, Link, STACObject
from shapely.geometry import shape
from shapely.geometry.base import BaseGeometry
from toolz import dicttoolz
from werkzeug.datastructures import TypeConversionDict
from werkzeug.exceptions import BadRequest, HTTPException
from cubedash.summary._stores import DatasetItem
from . import _model, _utils
from .summary import ItemSort
_LOG = logging.getLogger(__name__)
bp = flask.Blueprint("stac", __name__, url_prefix="/stac")
PAGE_SIZE_LIMIT = _model.app.config.get("STAC_PAGE_SIZE_LIMIT", 1000)
DEFAULT_PAGE_SIZE = _model.app.config.get("STAC_DEFAULT_PAGE_SIZE", 20)
DEFAULT_CATALOG_SIZE = _model.app.config.get("STAC_DEFAULT_CATALOG_SIZE", 500)
# Should we force all URLs to include the full hostname?
FORCE_ABSOLUTE_LINKS = _model.app.config.get("STAC_ABSOLUTE_HREFS", True)
# Should searches return the full properties for every stac item by default?
# These searches are much slower we're forced us to use ODC's own metadata table.
DEFAULT_RETURN_FULL_ITEMS = _model.app.config.get(
"STAC_DEFAULT_FULL_ITEM_INFORMATION", True
)
STAC_VERSION = "1.0.0"
ItemLike = Union[pystac.Item, dict]
############################
# Helpers
############################
def dissoc_in(d: dict, key: str):
# like dicttoolz.dissoc but with support for nested keys
split = key.split(".")
if len(split) > 1: # if nested
if dicttoolz.get_in(split, d) is not None:
outer = dicttoolz.get_in(split[:-1], d)
return dicttoolz.update_in(
d=d,
keys=split[:-1],
func=lambda _: dicttoolz.dissoc(outer, split[-1]), # noqa: B023
)
return dicttoolz.dissoc(d, key)
# Time-related
def utc(d: datetime):
if d.tzinfo is None:
return d.replace(tzinfo=tz.tzutc())
return d.astimezone(tz.tzutc())
def _parse_time_range(time: str) -> Optional[Tuple[datetime, datetime]]:
"""
>>> _parse_time_range('1986-04-16T01:12:16/2097-05-10T00:24:21')
(datetime.datetime(1986, 4, 16, 1, 12, 16), datetime.datetime(2097, 5, 10, 0, 24, 21))
>>> _parse_time_range('1986-04-16T01:12:16')
(datetime.datetime(1986, 4, 16, 1, 12, 16), datetime.datetime(1986, 4, 16, 1, 12, 17))
>>> # Time is optional:
>>> _parse_time_range('2019-01-01/2019-01-01')
(datetime.datetime(2019, 1, 1, 0, 0), datetime.datetime(2019, 1, 1, 0, 0))
>>> _parse_time_range('1986-04-16')
(datetime.datetime(1986, 4, 16, 0, 0), datetime.datetime(1986, 4, 17, 0, 0))
>>> # Open ranges:
>>> _parse_time_range('2019-01-01/..')[0]
datetime.datetime(2019, 1, 1, 0, 0)
>>> _parse_time_range('2019-01-01/..')[1] > datetime.now()
True
>>> _parse_time_range('../2019-01-01')
(datetime.datetime(1971, 1, 1, 0, 0), datetime.datetime(2019, 1, 1, 0, 0))
>>> # Unbounded time is the same as no time filter. ("None")
>>> _parse_time_range('../..')
>>>
"""
time_period = time.split("/")
if len(time_period) == 2:
start, end = time_period
if start == "..":
start = datetime(1971, 1, 1, 0, 0)
elif end == "..":
end = datetime.now() + timedelta(days=2)
# Were they both open? Treat it as no date filter.
if end == "..":
return None
return parse_time(start), parse_time(end)
elif len(time_period) == 1:
t: datetime = parse_time(time_period[0])
if t.time() == dt_time():
return t, t + timedelta(days=1)
else:
return t, t + timedelta(seconds=1)
def _unparse_time_range(time: Tuple[datetime, datetime]) -> str:
"""
>>> _unparse_time_range((
... datetime(1986, 4, 16, 1, 12, 16),
... datetime(2097, 5, 10, 0, 24, 21)
... ))
'1986-04-16T01:12:16/2097-05-10T00:24:21'
"""
start_time, end_time = time
return f"{start_time.isoformat()}/{end_time.isoformat()}"
# URL-related
def url_for(*args, **kwargs):
if FORCE_ABSOLUTE_LINKS:
kwargs["_external"] = True
return flask.url_for(*args, **kwargs)
def _pick_remote_uri(uris: Sequence[str]) -> Optional[int]:
"""
Return the offset of the first uri with a remote path, if any.
"""
for i, uri in enumerate(uris):
scheme, *_ = uri.split(":")
if scheme in ("https", "http", "ftp", "s3", "gfs"):
return i
return None
# Conversions
def _band_to_measurement(band: Dict, dataset_location: str) -> MeasurementDoc:
"""Create EO3 measurement from an EO1 band dict"""
return MeasurementDoc(
path=band.get("path"),
band=band.get("band"),
layer=band.get("layer"),
name=band.get("name"),
alias=band.get("label"),
)
def as_stac_item(dataset: DatasetItem) -> pystac.Item:
"""
Get a dict corresponding to a stac item
"""
ds: Dataset = dataset.odc_dataset
if ds is not None and is_doc_eo3(ds.metadata_doc):
dataset_doc = serialise.from_doc(ds.metadata_doc, skip_validation=True)
dataset_doc.locations = ds.uris
# Geometry is optional in eo3, and needs to be calculated from grids if missing.
# We can use ODC's own calculation that happens on index.
if dataset_doc.geometry is None:
fallback_extent = ds.extent
if fallback_extent is not None:
dataset_doc.geometry = fallback_extent.geom
dataset_doc.crs = str(ds.crs)
if ds.sources:
dataset_doc.lineage = {classifier: [d.id] for classifier, d in ds.sources}
# Does ODC still put legacy lineage into indexed documents?
elif ("source_datasets" in dataset_doc.lineage) and len(
dataset_doc.lineage
) == 1:
# From old to new lineage type.
dataset_doc.lineage = {
classifier: [dataset["id"]]
for classifier, dataset in dataset_doc.lineage["source_datasets"]
}
else:
# eo1 to eo3
dataset_doc = DatasetDoc(
id=dataset.dataset_id,
# Filled-in below.
label=None,
product=ProductDoc(dataset.product_name),
locations=ds.uris if ds is not None else None,
crs=str(dataset.geometry.crs) if dataset.geometry is not None else None,
geometry=dataset.geometry.geom if dataset.geometry is not None else None,
grids=None,
# TODO: Convert these from stac to eo3
properties=Eo3Dict(
{
"datetime": utc(dataset.center_time),
**(dict(_build_properties(ds.metadata)) if ds else {}),
"odc:processing_datetime": utc(dataset.creation_time),
}
),
measurements=(
{
name: _band_to_measurement(
b,
dataset_location=(
ds.uris[0] if ds is not None and ds.uris else None
),
)
for name, b in ds.measurements.items()
}
if ds is not None
else {}
),
accessories=(
_accessories_from_eo1(ds.metadata_doc) if ds is not None else {}
),
# TODO: Fill in lineage. The datacube API only gives us full datasets, which is
# expensive. We only need a list of IDs here.
lineage={},
)
if dataset_doc.label is None and ds is not None:
dataset_doc.label = _utils.dataset_label(ds)
item = eo3stac.to_pystac_item(
dataset=dataset_doc,
stac_item_destination_url=url_for(
".item",
collection=dataset.product_name,
dataset_id=dataset.dataset_id,
),
odc_dataset_metadata_url=url_for("dataset.raw_doc", id_=dataset.dataset_id),
explorer_base_url=url_for("default_redirect"),
)
# Add the region code that Explorer inferred.
# (Explorer's region codes predate ODC's and support
# many more products.
item.properties["cubedash:region_code"] = dataset.region_code
# add canonical ref pointing to the JSON file on s3
if ds is not None and ds.uris:
media_type = "application/json" if ds.uris[0].endswith("json") else "text/yaml"
item.links.append(
Link(
rel="canonical",
media_type=media_type,
target=_utils.as_resolved_remote_url(None, ds.uris[0]),
)
)
return item
def _accessories_from_eo1(metadata_doc: Dict) -> Dict[str, AccessoryDoc]:
"""Create and EO3 accessories section from an EO1 document"""
accessories = {}
# Browse image -> thumbnail
if "browse" in metadata_doc:
for name, browse in metadata_doc["browse"].items():
accessories[f"thumbnail:{name}"] = AccessoryDoc(
path=browse["path"], name=name
)
# Checksum
if "checksum_path" in metadata_doc:
accessories["checksum:sha1"] = AccessoryDoc(
path=metadata_doc["checksum_path"], name="checksum:sha1"
)
return accessories
def field_platform(key, value):
yield "eo:platform", value.lower().replace("_", "-")
def field_instrument(key, value):
yield "eo:instrument", value
def field_path_row(key, value):
# Path/Row fields are ranges in datacube but 99% of the time
# they are a single value
# (they are ranges in telemetry products)
# Stac doesn't accept a range here, so we'll skip it in those products,
# but we can handle the 99% case when lower==higher.
if key == "sat_path":
kind = "landsat:wrs_path"
elif key == "sat_row":
kind = "landsat:wrs_row"
else:
raise ValueError(f"Path/row kind {key!r}")
# If there's only one value in the range, return it.
if isinstance(value, Range):
if value.end is None or value.begin == value.end:
# Standard stac
yield kind, int(value.begin)
else:
# Our questionable output. Only present in telemetry products?
yield f"odc:{key}", [value.begin, value.end]
# Other Property examples:
# collection "landsat-8-l1"
# eo:gsd 15
# eo:platform "landsat-8"
# eo:instrument "OLI_TIRS"
# eo:off_nadir 0
# datetime "2019-02-12T19:26:08.449265+00:00"
# eo:sun_azimuth -172.29462212
# eo:sun_elevation -6.62176054
# eo:cloud_cover -1
# eo:row "135"
# eo:column "044"
# landsat:product_id "LC08_L1GT_044135_20190212_20190212_01_RT"
# landsat:scene_id "LC80441352019043LGN00"
# landsat:processing_level "L1GT"
# landsat:tier "RT"
_STAC_PROPERTY_MAP = {
"platform": field_platform,
"instrument": field_instrument,
# "measurements": field_bands,
"sat_path": field_path_row,
"sat_row": field_path_row,
}
def _build_properties(d: DocReader):
for key, val in d.fields.items():
if val is None:
continue
converter = _STAC_PROPERTY_MAP.get(key)
if converter:
yield from converter(key, val)
# Search arguments
def _remove_prefixes(arg: str):
# remove potential 'item.', 'properties.', or 'item.properties.' prefixes for ease of handling
arg = arg.replace("item.", "")
arg = arg.replace("properties.", "")
return arg
def _array_arg(
arg: Union[str, List[Union[str, float]]], expect_type=str, expect_size=None
) -> List:
"""
Parse an argument that should be a simple list.
"""
if isinstance(arg, list):
return arg
# Make invalid arguments loud. The default ValueError behaviour is to quietly forget the param.
try:
if not isinstance(arg, str):
raise ValueError
arg = arg.strip()
# Legacy json-like format. This is what sat-api seems to do too.
if arg.startswith("["):
value = json.loads(arg)
else:
# Otherwise OpenAPI non-exploded form style.
# Eg. "1, 2, 3" or "string1,string2" or "string1"
args = [a.strip() for a in arg.split(",")]
value = [expect_type(a.strip()) for a in args if a]
except ValueError:
raise BadRequest(
f"Invalid argument syntax. Expected comma-separated list, got: {arg!r}"
)
if not isinstance(value, list):
raise BadRequest(f"Invalid argument syntax. Expected json list, got: {value!r}")
if expect_size is not None and len(value) != expect_size:
raise BadRequest(
f"Expected size {expect_size}, got {len(value)} elements in {arg!r}"
)
return value
def _geojson_arg(arg: dict) -> BaseGeometry:
if not isinstance(arg, dict):
raise BadRequest(
"The 'intersects' argument must be a JSON object (and sent over a POST request)"
)
try:
return shape(arg)
except ValueError:
raise BadRequest("The 'intersects' argument must be valid GeoJSON geometry.")
def _bool_argument(s: Union[str, bool]):
"""
Parse an argument that should be a bool
"""
if isinstance(s, bool):
return s
# Copying FastAPI booleans:
# https://fastapi.tiangolo.com/tutorial/query-params
return s.strip().lower() in ("1", "true", "on", "yes")
def _dict_arg(arg: Union[str, dict]):
"""
Parse stac extension arguments as dicts
"""
if isinstance(arg, str):
arg = json.loads(arg.replace("'", '"'))
return arg
def _field_arg(arg: Union[str, list, dict]) -> dict[str, list[str]]:
"""
Parse field argument into a dict
"""
if isinstance(arg, dict):
return _dict_arg(arg)
if isinstance(arg, str):
if arg.startswith("{"):
return _dict_arg(arg)
arg = arg.split(",")
if isinstance(arg, list):
include = []
exclude = []
for a in arg:
if a.startswith("-"):
exclude.append(a[1:])
else:
# account for '+' showing up as a space if not encoded
include.append(a[1:] if a.startswith("+") else a.strip())
return {"include": include, "exclude": exclude}
def _sort_arg(arg: Union[str, list]) -> list[dict]:
"""
Parse sortby argument into a list of dicts
"""
def _format(val: str) -> dict[str, str]:
val = _remove_prefixes(val)
if val.startswith("-"):
return {"field": val[1:], "direction": "desc"}
if val.startswith("+"):
return {"field": val[1:], "direction": "asc"}
# default is ascending
return {"field": val.strip(), "direction": "asc"}
if isinstance(arg, str):
arg = arg.split(",")
if len(arg):
if isinstance(arg[0], str):
return [_format(a) for a in arg]
if isinstance(arg[0], dict):
for a in arg:
a["field"] = _remove_prefixes(a["field"])
return arg
def _filter_arg(arg: Union[str, dict]) -> str:
# convert dict to arg to more easily remove prefixes
if isinstance(arg, dict):
arg = json.dumps(arg)
return _remove_prefixes(arg)
def _validate_filter(filter_lang: str, cql: str):
# check filter-lang and actual cql format are aligned
is_json = True
try:
json.loads(cql)
except json.decoder.JSONDecodeError:
is_json = False
if filter_lang == "cql2-text" and is_json:
abort(400, "Expected filter to be cql2-text, but received cql2-json")
if filter_lang == "cql2-json" and not is_json:
abort(400, "Expected filter to be cql2-json, but received cql2-text")
# Search
def _handle_search_request(
method: str,
request_args: TypeConversionDict,
product_names: List[str],
include_total_count: bool = True,
) -> ItemCollection:
bbox = request_args.get(
"bbox", type=partial(_array_arg, expect_size=4, expect_type=float)
)
# Stac-api <=0.7.0 used 'time', later versions use 'datetime'
time = request_args.get("datetime") or request_args.get("time")
limit = request_args.get("limit", default=DEFAULT_PAGE_SIZE, type=int)
ids = request_args.get(
"ids", default=None, type=partial(_array_arg, expect_type=uuid.UUID)
)
offset = request_args.get("_o", default=0, type=int)
# Request the full Item information. This forces us to go to the
# ODC dataset table for every record, which can be extremely slow.
full_information = request_args.get(
"_full", default=DEFAULT_RETURN_FULL_ITEMS, type=_bool_argument
)
intersects = request_args.get("intersects", default=None, type=_geojson_arg)
fields = request_args.get("fields", default=None, type=_field_arg)
sortby = request_args.get("sortby", default=None, type=_sort_arg)
# not sure if there's a neater way to check sortable attribute type in _stores
# but the handling logic (i.e. 400 status code) would still need to live in here
if sortby:
for s in sortby:
field = s.get("field")
if field in [
"type",
"stac_version",
"properties",
"geometry",
"links",
"assets",
"bbox",
"stac_extensions",
]:
abort(
400,
f"Cannot sort by {field}. "
"Only 'id', 'collection', and Item properties can be used to sort results.",
)
filter_lang = request_args.get("filter-lang", default=None, type=str)
filter_cql = request_args.get("filter", default=None, type=_filter_arg)
filter_crs = request_args.get("filter-crs", default=None)
if filter_crs and filter_crs != "https://www.opengis.net/def/crs/OGC/1.3/CRS84":
abort(
400,
"filter-crs only accepts 'https://www.opengis.net/def/crs/OGC/1.3/CRS84' as a valid value.",
)
if filter_lang is None and filter_cql is not None:
# If undefined, defaults to cql2-text for a GET request and cql2-json for a POST request.
if method == "GET":
filter_lang = "cql2-text"
else:
filter_lang = "cql2-json"
if filter_cql:
_validate_filter(filter_lang, filter_cql)
if limit > PAGE_SIZE_LIMIT:
abort(
400,
f"Max page size is {PAGE_SIZE_LIMIT}. "
f"Use the next links instead of a large limit.",
)
if bbox is not None and len(bbox) != 4:
abort(400, "Expected bbox of size 4. [min lon, min lat, max long, max lat]")
if time is not None:
time = _parse_time_range(time)
def next_page_url(next_offset):
return url_for(
".stac_search",
collections=",".join(product_names),
bbox="{},{},{},{}".format(*bbox) if bbox else None,
time=_unparse_time_range(time) if time else None,
ids=",".join(map(str, ids)) if ids else None,
limit=limit,
_o=next_offset,
_full=full_information,
intersects=intersects,
fields=fields,
sortby=sortby,
# so that it doesn't get named 'filter_lang'
**{"filter-lang": filter_lang},
filter=filter_cql,
)
feature_collection = search_stac_items(
product_names=product_names,
bbox=bbox,
time=time,
dataset_ids=ids,
limit=limit,
offset=offset,
intersects=intersects,
# The /stac/search api only supports intersects over post requests.
use_post_request=method == "POST" or intersects is not None,
get_next_url=next_page_url,
full_information=full_information,
include_total_count=include_total_count,
fields=fields,
sortby=sortby,
filter_lang=filter_lang,
filter_cql=filter_cql,
)
feature_collection.extra_fields["links"].extend(
(
dict(
href=url_for(".stac_search"),
rel="search",
title="Search",
type="application/geo+json",
method="GET",
),
dict(
href=url_for(".stac_search"),
rel="search",
title="Search",
type="application/geo+json",
method="POST",
),
)
)
return feature_collection
# Item search extensions
def _get_property(prop: str, item: ItemLike, no_default=False):
"""So that we don't have to keep using this bulky expression"""
if isinstance(item, pystac.Item):
item = item.to_dict()
return dicttoolz.get_in(prop.split("."), item, no_default=no_default)
def _handle_fields_extension(items: List[ItemLike], fields: dict) -> List[ItemLike]:
"""
Implementation of fields extension (https://github.com/stac-api-extensions/fields/blob/main/README.md)
This implementation differs slightly from the documented semantics in that the default fields will always
be included regardless of `include` or `exclude` values so as to ensure valid stac items.
fields = {'include': [...], 'exclude': [...]}
"""
res = []
for item in items:
# minimum fields needed for a valid stac item
default_fields = [
"id",
"type",
"geometry",
"bbox",
"links",
"assets",
"stac_version",
# while not necessary for a valid stac item, we still want them included
"stac_extensions",
"collection",
]
# datetime is one of the default fields, but might be included as start_datetime/end_datetime instead
if _get_property("properties.start_datetime", item) is None:
dt_field = ["properties.start_datetime", "properties.end_datetime"]
else:
dt_field = ["properties.datetime"]
try:
# if 'include' is present at all, start with default fields to add to or extract from
include = fields["include"]
if include is None:
include = []
filtered_item = {k: _get_property(k, item) for k in default_fields}
# handle datetime separately due to nested keys
for f in dt_field:
filtered_item = dicttoolz.assoc_in(
filtered_item, f.split("."), _get_property(f, item)
)
except KeyError:
# if 'include' wasn't provided, remove 'exclude' fields from set of all available fields
filtered_item = item.to_dict()
include = []
# add datetime field names to list of defaults for easy access
default_fields.extend(dt_field)
include = list(set(include + default_fields))
for exc in fields.get("exclude", []):
if exc not in default_fields:
filtered_item = dissoc_in(filtered_item, exc)
# include takes precedence over exclude, plus account for a nested field of an excluded field
for inc in include:
# we don't want to insert None values if a field doesn't exist, but we also don't want to error
try:
filtered_item = dicttoolz.update_in(
d=filtered_item,
keys=inc.split("."),
func=lambda _: _get_property(
inc,
item,
no_default=True, # noqa: B023
),
)
except KeyError:
continue
res.append(filtered_item)
return res
def search_stac_items(
get_next_url: Callable[[int], str],
limit: int = DEFAULT_PAGE_SIZE,
offset: int = 0,
dataset_ids: Optional[str] = None,
product_names: Optional[List[str]] = None,
bbox: Optional[Tuple[float, float, float, float]] = None,
intersects: Optional[BaseGeometry] = None,
time: Optional[Tuple[datetime, datetime]] = None,
full_information: bool = False,
order: ItemSort = ItemSort.DEFAULT_SORT,
include_total_count: bool = False,
use_post_request: bool = False,
fields: Optional[dict] = None,
sortby: Optional[List[dict]] = None,
filter_lang: Optional[str] = None,
filter_cql: Optional[str | dict] = None,
) -> ItemCollection:
"""
Perform a search, returning a FeatureCollection of stac Item results.
:param get_next_url: A function that calculates a page url for the given offset.
"""
offset = offset or 0
if sortby is not None:
order = sortby
items = list(
_model.STORE.search_items(
product_names=product_names,
time=time,
bbox=bbox,
limit=limit + 1,
dataset_ids=dataset_ids,
intersects=intersects,
offset=offset,
full_dataset=full_information,
filter_lang=filter_lang,
filter_cql=filter_cql,
order=order,
)
)
returned = items[:limit]
there_are_more = len(items) == limit + 1
page = 0
if limit != 0:
page = offset // limit
extra_properties = dict(
links=[],
# Stac standard
numberReturned=len(returned),
# Compatibility with older implementation. Was removed from stac-api standard.
# (page numbers + limits are not ideal as they prevent some big db optimisations.)
context=dict(
page=page,
limit=limit,
returned=len(returned),
),
)
if include_total_count:
count_matching = _model.STORE.get_count(
product_names=product_names,
time=time,
bbox=bbox,
intersects=intersects,
dataset_ids=dataset_ids,
filter_lang=filter_lang,
filter_cql=filter_cql,
)
extra_properties["numberMatched"] = count_matching
extra_properties["context"]["matched"] = count_matching
items = [as_stac_item(f) for f in returned]
items = _handle_fields_extension(items, fields) if fields else items
result = ItemCollection(items, extra_fields=extra_properties)
if there_are_more:
next_link = dict(
rel="next",
title="Next page of Items",
type="application/geo+json",
)
if use_post_request:
next_link.update(
dict(
method="POST",
merge=True,
# Unlike GET requests, we can tell them to repeat their same request args
# themselves.
#
# Same URL:
href=flask.request.url,
# ... with a new offset.
body=dict(
_o=offset + limit,
),
)
)
else:
# Otherwise, let the route create the next url.
next_link.update(
dict(
method="GET",
href=get_next_url(offset + limit),
)
)
result.extra_fields["links"].append(next_link)
return result
# Response helpers
def _stac_collection(collection: str) -> Collection:
summary = _model.get_product_summary(collection)
try:
dataset_type = _model.STORE.get_dataset_type(collection)
except KeyError:
abort(404, f"Unknown collection {collection!r}")
all_time_summary = _model.get_time_summary(collection)
begin, end = (
(summary.time_earliest, summary.time_latest) if summary else (None, None)
)
footprint = all_time_summary.footprint_wgs84
if "title" in dataset_type.definition.get("metadata"):
title = dataset_type.definition.get("metadata")["title"]
else:
title = summary.name
stac_collection = Collection(
id=summary.name,
title=title,
license=_utils.product_license(dataset_type),
description=dataset_type.definition.get("description"),
providers=[],
extent=Extent(
pystac.SpatialExtent(
bboxes=[footprint.bounds if footprint else [-180.0, -90.0, 180.0, 90.0]]
),
temporal=pystac.TemporalExtent(
intervals=[
[
utc(begin) if begin else None,
utc(end) if end else None,
]
]
),
),
)
stac_collection.set_root(root_catalog())
stac_collection.links.extend(
[
Link(rel="self", target=request.url),
Link(
rel="items",
target=url_for(".collection_items", collection=collection),
),
Link(
rel="http://www.opengis.net/def/rel/ogc/1.0/queryables",
target=url_for(".collection_queryables", collection=collection),
),
]
)
if all_time_summary.timeline_dataset_counts:
stac_collection.links.extend(
Link(
rel="child",
target=url_for(
".collection_month",
collection=collection,
year=date.year,
month=date.month,
),
)
for date, count in all_time_summary.timeline_dataset_counts.items()
if count > 0
)
return stac_collection
def _stac_response(
doc: Union[STACObject, ItemCollection], content_type="application/json"
) -> flask.Response:
"""Return a stac document as the flask response"""
if isinstance(doc, STACObject):
doc.set_root(root_catalog())
return _utils.as_json(
doc.to_dict(),
content_type=content_type,
)
def _geojson_stac_response(doc: Union[STACObject, ItemCollection]) -> flask.Response:
"""Return a stac item"""
return _stac_response(doc, content_type="application/geo+json")
# Root setup
def stac_endpoint_information() -> Dict:
config = _model.app.config
o = dict(
id=config.get("STAC_ENDPOINT_ID", "odc-explorer"),
title=config.get("STAC_ENDPOINT_TITLE", "Default ODC Explorer instance"),
)
description = config.get(
"STAC_ENDPOINT_DESCRIPTION",
"Configure stac endpoint information in your Explorer `settings.env.py` file",
)
if description:
o["description"] = description
return o
def root_catalog():
c = Catalog(
**stac_endpoint_information(),
)
c.set_self_href(url_for(".root"))
return c
##########################
# ENDPOINTS
##########################
@bp.route("", strict_slashes=False)
def root():
"""
The root stac page links to each collection (product) catalog
"""
c = root_catalog()
c.links.extend(
[
Link(
title="Collections",
# description="All product collections",
rel="children",
media_type="application/json",
target=url_for(".collections"),
),
Link(
title="Arrivals",
# description="Most recently added items",
rel="child",
media_type="application/json",
target=url_for(".arrivals"),
),
Link(
title="Item Search",
rel="search",
media_type="application/json",
target=url_for(".stac_search"),
),
Link(
title="Queryables",
rel="http://www.opengis.net/def/rel/ogc/1.0/queryables",