|
| 1 | +# |
| 2 | +# This file is part of Cube Builder. |
| 3 | +# Copyright (C) 2022 INPE. |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>. |
| 17 | +# |
| 18 | + |
| 19 | +"""Define basic module to adapt Python libraries like STAC v1 and legacy versions.""" |
| 20 | + |
| 21 | +from abc import ABC, abstractmethod |
| 22 | +from copy import deepcopy |
| 23 | +from typing import List |
| 24 | +from urllib.parse import urljoin |
| 25 | + |
| 26 | +import requests |
| 27 | +import shapely.geometry |
| 28 | +from pystac_client import Client |
| 29 | +from werkzeug.exceptions import abort |
| 30 | + |
| 31 | + |
| 32 | +class BaseSTAC(ABC): |
| 33 | + """Define base class to represent a STAC interface to communicate with Server.""" |
| 34 | + |
| 35 | + uri: str |
| 36 | + """Represent URI for server.""" |
| 37 | + headers: dict |
| 38 | + """Represent HTTP headers to be attached in requests.""" |
| 39 | + params: dict |
| 40 | + """Represent HTTP parameters for requests.""" |
| 41 | + |
| 42 | + def __init__(self, uri: str, params=None, headers=None, **kwargs): |
| 43 | + """Build STAC signature.""" |
| 44 | + self.uri = uri |
| 45 | + self.params = params |
| 46 | + self.headers = headers |
| 47 | + self._options = kwargs |
| 48 | + |
| 49 | + @abstractmethod |
| 50 | + def search(self, **parameters) -> dict: |
| 51 | + """Search for collection items on STAC server.""" |
| 52 | + |
| 53 | + @abstractmethod |
| 54 | + def items(self, collection_id: str, **kwargs) -> dict: |
| 55 | + """Access STAC Collection Items.""" |
| 56 | + |
| 57 | + @abstractmethod |
| 58 | + def collections(self) -> List[dict]: |
| 59 | + """Retrieve the collections from STAC.""" |
| 60 | + |
| 61 | + @abstractmethod |
| 62 | + def collection(self, collection_id: str) -> dict: |
| 63 | + """Access STAC Collection.""" |
| 64 | + |
| 65 | + @staticmethod |
| 66 | + def _items_result(features: List[dict], matched: int): |
| 67 | + return { |
| 68 | + "context": { |
| 69 | + "returned": len(features), |
| 70 | + "matched": matched |
| 71 | + }, |
| 72 | + "features": features |
| 73 | + } |
| 74 | + |
| 75 | + |
| 76 | +class STACV1(BaseSTAC): |
| 77 | + """Define structure to add support for STAC v1.0+. |
| 78 | +
|
| 79 | + This implementation uses `pystac-client <https://pystac-client.readthedocs.io/en/latest/>`_ |
| 80 | + to communicate with STAC v1.0. |
| 81 | + """ |
| 82 | + |
| 83 | + def __init__(self, uri: str, params=None, headers=None, **kwargs): |
| 84 | + """Build STAC instance.""" |
| 85 | + super(STACV1, self).__init__(uri, params, headers, **kwargs) |
| 86 | + |
| 87 | + self._instance = Client.open(uri, headers=headers, parameters=params, **kwargs) |
| 88 | + |
| 89 | + def search(self, limit=10, max_items=10, **parameters) -> dict: |
| 90 | + """Search for collection items on STAC server.""" |
| 91 | + max_items = limit |
| 92 | + item_search = self._instance.search(limit=limit, max_items=max_items, **parameters) |
| 93 | + |
| 94 | + items = item_search.items() |
| 95 | + items = [i.to_dict() for i in items] |
| 96 | + |
| 97 | + return self._items_result(items, matched=item_search.matched()) |
| 98 | + |
| 99 | + def collections(self) -> List[dict]: |
| 100 | + """Retrieve the collections from STAC.""" |
| 101 | + return [c.to_dict() for c in self._instance.get_collections()] |
| 102 | + |
| 103 | + def collection(self, collection_id: str) -> dict: |
| 104 | + """Access STAC Collection.""" |
| 105 | + collection = self._instance.get_collection(collection_id) |
| 106 | + return collection.to_dict() |
| 107 | + |
| 108 | + def items(self, collection_id: str, **kwargs) -> dict: |
| 109 | + """Access STAC Collection Items.""" |
| 110 | + collection = self._instance.get_collection(collection_id) |
| 111 | + |
| 112 | + items = collection.get_items() |
| 113 | + items = [i.to_dict() for i in items] |
| 114 | + |
| 115 | + result = self.search(collections=[collection_id], limit=1, max_items=1) |
| 116 | + |
| 117 | + return self._items_result(items, matched=result['context']['matched']) |
| 118 | + |
| 119 | + |
| 120 | +class STACLegacy(BaseSTAC): |
| 121 | + """Define structure to add support for legacy versions of STAC server.. |
| 122 | +
|
| 123 | + This implementation uses `requests.Session <https://requests.readthedocs.io/en/latest/user/advanced/#session-objects>`_ |
| 124 | + to communicate with STAC legacy versions 0.8x, 0.9x directly. |
| 125 | +
|
| 126 | + By default, the ssl entries are ignored. You may override this setting using ``verify=False``. |
| 127 | + """ |
| 128 | + |
| 129 | + def __init__(self, uri: str, params=None, headers=None, verify=False, **kwargs): |
| 130 | + """Build STAC instance.""" |
| 131 | + super(STACLegacy, self).__init__(uri, params, headers, **kwargs) |
| 132 | + |
| 133 | + params = params or {} |
| 134 | + headers = headers or {} |
| 135 | + |
| 136 | + self._params = params |
| 137 | + self._headers = headers |
| 138 | + self._session = requests.session() |
| 139 | + self._session.verify = verify |
| 140 | + |
| 141 | + def search(self, **parameters) -> dict: |
| 142 | + """Search for collection items on STAC server.""" |
| 143 | + options = deepcopy(parameters) |
| 144 | + # Remove unsupported values |
| 145 | + options.pop('query', None) |
| 146 | + url = self._url_resource('search') |
| 147 | + |
| 148 | + try: |
| 149 | + response = self._request(url, method='POST', data=options, headers=self._headers, params=self._params) |
| 150 | + except: |
| 151 | + # Use bbox instead |
| 152 | + geom = options.pop('intersects', None) |
| 153 | + if geom is None: |
| 154 | + raise |
| 155 | + |
| 156 | + options['bbox'] = shapely.geometry.shape(geom).bounds |
| 157 | + |
| 158 | + response = self._request(url, method='POST', data=options, headers=self._headers, params=self._params) |
| 159 | + |
| 160 | + return response |
| 161 | + |
| 162 | + def _request(self, uri: str, method: str = 'GET', data=None, headers=None, params=None): |
| 163 | + response = self._session.request(method, uri, headers=headers, params=params, json=data) |
| 164 | + if response.status_code != 200: |
| 165 | + abort(response.status_code, response.content) |
| 166 | + return response.json() |
| 167 | + |
| 168 | + def collections(self) -> List[dict]: |
| 169 | + """Retrieve the collections from STAC.""" |
| 170 | + uri = self._url_resource('collections') |
| 171 | + collections = self._request(uri, params=self._params, headers=self._headers) |
| 172 | + return collections |
| 173 | + |
| 174 | + def collection(self, collection_id: str) -> dict: |
| 175 | + """Access STAC Collection.""" |
| 176 | + uri = self._url_resource(f'collections/{collection_id}') |
| 177 | + collection = self._request(uri, params=self._params, headers=self._headers) |
| 178 | + return collection |
| 179 | + |
| 180 | + def items(self, collection_id: str, **kwargs) -> dict: |
| 181 | + """Access STAC Collection Items.""" |
| 182 | + return self.search(collections=[collection_id], limit=1) |
| 183 | + |
| 184 | + def _url_resource(self, resource: str) -> str: |
| 185 | + return urljoin(self.uri + '/', resource) |
| 186 | + |
| 187 | + |
| 188 | +def build_stac(uri, headers=None, **parameters) -> BaseSTAC: |
| 189 | + """Build a STAC instance according versions.""" |
| 190 | + response = requests.get(uri, timeout=15, headers=headers, params=parameters) |
| 191 | + |
| 192 | + response.raise_for_status() |
| 193 | + |
| 194 | + catalog = response.json() |
| 195 | + if not catalog.get('stac_version'): |
| 196 | + raise RuntimeError(f'Invalid STAC "{uri}", missing "stac_version"') |
| 197 | + |
| 198 | + stac_version = catalog['stac_version'] |
| 199 | + if stac_version.startswith('0.'): |
| 200 | + return STACLegacy(uri, params=parameters, headers=headers) |
| 201 | + return STACV1(uri, params=parameters, headers=headers) |
0 commit comments