-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathlinks.py
308 lines (248 loc) · 9.57 KB
/
links.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
"""link helpers."""
from typing import Any, Dict, List, Optional
from urllib.parse import ParseResult, parse_qs, unquote, urlencode, urljoin, urlparse
import attr
from stac_fastapi.types.requests import get_base_url
from stac_pydantic.links import Relations
from stac_pydantic.shared import MimeTypes
from starlette.requests import Request
# These can be inferred from the item/collection so they aren't included in the database
# Instead they are dynamically generated when querying the database using the classes defined below
INFERRED_LINK_RELS = ["self", "item", "parent", "collection", "root"]
def filter_links(links: List[Dict]) -> List[Dict]:
"""Remove inferred links."""
return [link for link in links if link["rel"] not in INFERRED_LINK_RELS]
def merge_params(url: str, newparams: Dict) -> str:
"""Merge url parameters."""
u = urlparse(url)
params = parse_qs(u.query)
params.update(newparams)
param_string = unquote(urlencode(params, True))
href = ParseResult(
scheme=u.scheme,
netloc=u.netloc,
path=u.path,
params=u.params,
query=param_string,
fragment=u.fragment,
).geturl()
return href
@attr.s
class BaseLinks:
"""Create inferred links common to collections and items."""
request: Request = attr.ib()
@property
def base_url(self):
"""Get the base url."""
return get_base_url(self.request)
@property
def url(self):
"""Get the current request url."""
return str(self.request.url)
def resolve(self, url):
"""Resolve url to the current request url."""
return urljoin(str(self.base_url), str(url))
def link_self(self) -> Dict:
"""Return the self link."""
return {
"rel": Relations.self.value,
"type": MimeTypes.json.value,
"href": self.url,
}
def link_root(self) -> Dict:
"""Return the catalog root."""
return {
"rel": Relations.root.value,
"type": MimeTypes.json.value,
"href": self.base_url,
}
def create_links(self) -> List[Dict[str, Any]]:
"""Return all inferred links."""
links = []
for name in dir(self):
if name.startswith("link_") and callable(getattr(self, name)):
link = getattr(self, name)()
if link is not None:
links.append(link)
return links
async def get_links(
self, extra_links: Optional[List[Dict[str, Any]]] = None
) -> List[Dict[str, Any]]:
"""
Generate all the links.
Get the links object for a stac resource by iterating through
available methods on this class that start with link_.
"""
# TODO: Pass request.json() into function so this doesn't need to be coroutine
if self.request.method == "POST":
self.request.postbody = await self.request.json()
# join passed in links with generated links
# and update relative paths
links = self.create_links()
if extra_links:
# For extra links passed in,
# add links modified with a resolved href.
# Drop any links that are dynamically
# determined by the server (e.g. self, parent, etc.)
# Resolving the href allows for relative paths
# to be stored in pgstac and for the hrefs in the
# links of response STAC objects to be resolved
# to the request url.
links += [
{**link, "href": self.resolve(link["href"])}
for link in extra_links
if link["rel"] not in INFERRED_LINK_RELS
]
return links
@attr.s
class PagingLinks(BaseLinks):
"""Create links for paging."""
next: Optional[str] = attr.ib(kw_only=True, default=None)
prev: Optional[str] = attr.ib(kw_only=True, default=None)
def link_next(self) -> Optional[Dict[str, Any]]:
"""Create link for next page."""
if self.next is not None:
method = self.request.method
if method == "GET":
href = merge_params(self.url, {"token": f"next:{self.next}"})
link = {
"rel": Relations.next.value,
"type": MimeTypes.geojson.value,
"method": method,
"href": href,
}
return link
if method == "POST":
return {
"rel": Relations.next,
"type": MimeTypes.geojson,
"method": method,
"href": f"{self.request.url}",
"body": {**self.request.postbody, "token": f"next:{self.next}"},
}
return None
def link_prev(self) -> Optional[Dict[str, Any]]:
"""Create link for previous page."""
if self.prev is not None:
method = self.request.method
if method == "GET":
href = merge_params(self.url, {"token": f"prev:{self.prev}"})
return {
"rel": Relations.previous.value,
"type": MimeTypes.geojson.value,
"method": method,
"href": href,
}
if method == "POST":
return {
"rel": Relations.previous,
"type": MimeTypes.geojson,
"method": method,
"href": f"{self.request.url}",
"body": {**self.request.postbody, "token": f"prev:{self.prev}"},
}
return None
@attr.s
class CollectionSearchPagingLinks(BaseLinks):
next: Optional[Dict[str, Any]] = attr.ib(kw_only=True, default=None)
prev: Optional[Dict[str, Any]] = attr.ib(kw_only=True, default=None)
def link_next(self) -> Optional[Dict[str, Any]]:
"""Create link for next page."""
if self.next is not None:
method = self.request.method
if method == "GET":
# if offset is equal to default value (0), drop it
if self.next["body"].get("offset", -1) == 0:
_ = self.next["body"].pop("offset")
href = merge_params(self.url, self.next["body"])
# if next link is equal to this link, skip it
if href == self.url:
return None
return {
"rel": Relations.next.value,
"type": MimeTypes.geojson.value,
"method": method,
"href": href,
}
return None
def link_prev(self):
if self.prev is not None:
method = self.request.method
if method == "GET":
href = merge_params(self.url, self.prev["body"])
# if prev link is equal to this link, skip it
if href == self.url:
return None
return {
"rel": Relations.previous.value,
"type": MimeTypes.geojson.value,
"method": method,
"href": href,
}
return None
@attr.s
class CollectionLinksBase(BaseLinks):
"""Create inferred links specific to collections."""
collection_id: str = attr.ib()
def collection_link(self, rel: str = Relations.collection.value) -> Dict:
"""Create a link to a collection."""
return {
"rel": rel,
"type": MimeTypes.json.value,
"href": self.resolve(f"collections/{self.collection_id}"),
}
@attr.s
class CollectionLinks(CollectionLinksBase):
"""Create inferred links specific to collections."""
def link_self(self) -> Dict:
"""Return the self link."""
return self.collection_link(rel=Relations.self.value)
def link_parent(self) -> Dict:
"""Create the `parent` link."""
return {
"rel": Relations.parent.value,
"type": MimeTypes.json.value,
"href": self.base_url,
}
def link_items(self) -> Dict:
"""Create the `item` link."""
return {
"rel": "items",
"type": MimeTypes.geojson.value,
"href": self.resolve(f"collections/{self.collection_id}/items"),
}
@attr.s
class ItemCollectionLinks(CollectionLinksBase):
"""Create inferred links specific to collections."""
def link_self(self) -> Dict:
"""Return the self link."""
return {
"rel": Relations.self.value,
"type": MimeTypes.geojson.value,
"href": self.resolve(f"collections/{self.collection_id}/items"),
}
def link_parent(self) -> Dict:
"""Create the `parent` link."""
return self.collection_link(rel=Relations.parent.value)
def link_collection(self) -> Dict:
"""Create the `collection` link."""
return self.collection_link()
@attr.s
class ItemLinks(CollectionLinksBase):
"""Create inferred links specific to items."""
item_id: str = attr.ib()
def link_self(self) -> Dict:
"""Create the self link."""
return {
"rel": Relations.self.value,
"type": MimeTypes.geojson.value,
"href": self.resolve(
f"collections/{self.collection_id}/items/{self.item_id}"
),
}
def link_parent(self) -> Dict:
"""Create the `parent` link."""
return self.collection_link(rel=Relations.parent.value)
def link_collection(self) -> Dict:
"""Create the `collection` link."""
return self.collection_link()