This repository has been archived by the owner on Jul 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
372 lines (329 loc) · 13.1 KB
/
handlers.go
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
// Copyright 2016, RadiantBlue Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package planet
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/venicegeo/bf-ia-broker/util"
"github.com/venicegeo/geojson-go/geojson"
)
const noPlanetKey = "This operation requires a Planet Labs API key."
const noPlanetImageID = "This operation requires a Planet Labs image ID."
const invalidCloudCover = "Cloud Cover value of %v is invalid."
// DiscoverHandler is a handler for /planet/discover
// @Title planetDiscoverHandler
// @Description discovers scenes from Planet Labs
// @Accept plain
// @Param PL_API_KEY query string true "Planet Labs API Key"
// @Param itemType path string true "Planet Labs Item Type, e.g., rapideye or planetscope"
// @Param bbox query string false "The bounding box, as a GeoJSON Bounding box (x1,y1,x2,y2)"
// @Param cloudCover query string false "The maximum cloud cover, as a percentage (0-100)"
// @Param acquiredDate query string false "The minimum (earliest) acquired date, as RFC 3339"
// @Param maxAcquiredDate query string false "The maximum acquired date, as RFC 3339"
// @Param tides query bool false "True: incorporate tide prediction in the output"
// @Success 200 {object} geojson.FeatureCollection
// @Failure 400 {object} string
// @Router /planet/discover/{itemType} [get]
type DiscoverHandler struct {
Context Context
}
// NewDiscoverHandler creates a new handler using configuration
// from environment variables
func NewDiscoverHandler() DiscoverHandler {
planetBaseURL := util.GetPlanetAPIURL()
tidesURL := util.GetTidesURL()
return DiscoverHandler{
Context: Context{
BasePlanetURL: planetBaseURL,
BaseTidesURL: tidesURL,
},
}
}
// ServeHTTP implements the http.Handler interface for the DiscoverHandler type
func (h DiscoverHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
var (
fc *geojson.FeatureCollection
err error
itemType string
bytes []byte
bbox geojson.BoundingBox
ccStr string
cloudCover float64
)
util.LogAudit(&h.Context, util.LogAuditInput{Actor: "anon user", Action: request.Method, Actee: request.URL.String(), Message: "Receiving /planet/discover request", Severity: util.INFO})
if util.Preflight(writer, request, &h.Context) {
return
}
h.Context.PlanetKey = request.FormValue("PL_API_KEY")
if h.Context.PlanetKey == "" {
util.LogSimpleErr(&h.Context, noPlanetKey, nil)
util.HTTPError(request, writer, &h.Context, noPlanetKey, http.StatusBadRequest)
return
}
tides, _ := strconv.ParseBool(request.FormValue("tides"))
ccStr = request.FormValue("cloudCover")
if ccStr != "" {
if cloudCover, err = strconv.ParseFloat(ccStr, 64); err != nil {
message := fmt.Sprintf(invalidCloudCover, ccStr)
util.LogSimpleErr(&h.Context, message, err)
util.HTTPError(request, writer, &h.Context, message, http.StatusBadRequest)
return
}
cloudCover = cloudCover / 100.0
}
itemType = mux.Vars(request)["itemType"]
switch itemType {
case "REOrthoTile", "rapideye":
itemType = "REOrthoTile"
case "PSOrthoTile", "planetscope":
itemType = "PSOrthoTile"
case "Landsat8L1G", "landsat":
itemType = "Landsat8L1G"
case "Sentinel2L1C", "sentinel_s3", "sentinel_planet":
itemType = "Sentinel2L1C"
case "PSScene4Band":
// No op
default:
message := fmt.Sprintf("The item type value of %v is invalid", itemType)
util.LogSimpleErr(&h.Context, message, nil)
util.HTTPError(request, writer, &h.Context, message, http.StatusBadRequest)
return
}
bboxString := request.FormValue("bbox")
if bboxString != "" {
if bbox, err = geojson.NewBoundingBox(bboxString); err != nil {
message := fmt.Sprintf("The bbox value of %v is invalid", bboxString)
util.LogSimpleErr(&h.Context, message, err)
util.HTTPError(request, writer, &h.Context, message, http.StatusBadRequest)
return
}
}
options := SearchOptions{
ItemType: itemType,
CloudCover: cloudCover,
AcquiredDate: request.FormValue("acquiredDate"),
MaxAcquiredDate: request.FormValue("maxAcquiredDate"),
Tides: tides,
Bbox: bbox}
if fc, err = GetScenes(options, &h.Context); err != nil {
switch herr := err.(type) {
case util.HTTPErr:
util.HTTPError(request, writer, &h.Context, herr.Message, herr.Status)
default:
err = util.LogSimpleErr(&h.Context, "Failed to get Planet Labs scenes. ", err)
util.HTTPError(request, writer, &h.Context, err.Error(), http.StatusInternalServerError)
}
}
if bytes, err = geojson.Write(fc); err != nil {
err = util.LogSimpleErr(&h.Context, fmt.Sprintf("Failed to write output GeoJSON from:\n%#v", fc), err)
util.HTTPError(request, writer, &h.Context, err.Error(), http.StatusInternalServerError)
return
}
writer.Header().Set("Content-Type", "application/json")
writer.Write(bytes)
util.LogAudit(&h.Context, util.LogAuditInput{Actor: "anon user", Action: request.Method + " response", Actee: request.URL.String(), Message: "Sending /planet/discover response", Severity: util.INFO})
}
// MetadataHandler is a handler for /planet
// @Title planetMetadataHandler
// @Description Gets image metadata from Planet Labs
// @Accept plain
// @Param PL_API_KEY query string true "Planet Labs API Key"
// @Param itemType path string true "Planet Labs Item Type, e.g., rapideye or planetscope"
// @Param id path string true "Planet Labs image ID"
// @Param tides query bool false "True: incorporate tide prediction in the output"
// @Success 200 {object} geojson.Feature
// @Failure 400 {object} string
// @Router /planet/{itemType}/{id} [get]
type MetadataHandler struct {
Context Context
}
// NewMetadataHandler creates a new handler using configuration
// from environment variables
func NewMetadataHandler() MetadataHandler {
planetBaseURL := util.GetPlanetAPIURL()
tidesURL := util.GetTidesURL()
return MetadataHandler{
Context: Context{
BasePlanetURL: planetBaseURL,
BaseTidesURL: tidesURL,
},
}
}
// ServeHTTP implements the http.Handler interface for the MetadataHandler type
func (h MetadataHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
var (
err error
feature *geojson.Feature
bytes []byte
options MetadataOptions
)
util.LogAudit(&h.Context, util.LogAuditInput{Actor: "anon user", Action: request.Method, Actee: request.URL.String(), Message: "Receiving /planet/{itemType}/{id} request", Severity: util.INFO})
if util.Preflight(writer, request, &h.Context) {
return
}
vars := mux.Vars(request)
options.ID = vars["id"]
if options.ID == "" {
util.LogSimpleErr(&h.Context, noPlanetImageID, nil)
util.HTTPError(request, writer, &h.Context, noPlanetImageID, http.StatusBadRequest)
return
}
h.Context.PlanetKey = request.FormValue("PL_API_KEY")
if h.Context.PlanetKey == "" {
util.LogAlert(&h.Context, noPlanetKey)
util.HTTPError(request, writer, &h.Context, noPlanetKey, http.StatusBadRequest)
return
}
options.Tides, _ = strconv.ParseBool(request.FormValue("tides"))
itemType := vars["itemType"]
switch itemType {
case "REOrthoTile", "rapideye":
options.ItemType = "REOrthoTile"
options.ImagerySource = rapidEye
case "PSOrthoTile", "planetscope":
options.ItemType = "PSOrthoTile"
options.ImagerySource = planetScope
case "Landsat8L1G", "landsat":
options.ItemType = "Landsat8L1G"
options.ImagerySource = landsatFromS3
case "Sentinel2L1C", "sentinel_planet":
options.ItemType = "Sentinel2L1C"
options.ImagerySource = sentinelFromPlanet
case "sentinel_s3":
options.ItemType = "Sentinel2L1C"
options.ImagerySource = sentinelFromS3
case "PSScene4Band":
// No op
default:
message := fmt.Sprintf("The item type value of %v is invalid", itemType)
util.LogSimpleErr(&h.Context, message, nil)
util.HTTPError(request, writer, &h.Context, message, http.StatusBadRequest)
return
}
if feature, err = GetItemWithAssetMetadata(&h.Context, options); err != nil {
switch herr := err.(type) {
case util.HTTPErr:
util.HTTPError(request, writer, &h.Context, herr.Message, herr.Status)
default:
err = util.LogSimpleErr(&h.Context, "Failed to get Planet Labs scene metadata. ", err)
util.HTTPError(request, writer, &h.Context, err.Error(), 0)
}
}
if bytes, err = geojson.Write(feature); err != nil {
err = util.LogSimpleErr(&h.Context, fmt.Sprintf("Failed to write output GeoJSON from:\n%#v", feature), err)
util.HTTPError(request, writer, &h.Context, err.Error(), http.StatusInternalServerError)
return
}
writer.Header().Set("Content-Type", "application/json")
writer.Write(bytes)
util.LogAudit(&h.Context, util.LogAuditInput{Actor: request.URL.String(), Action: request.Method + " response", Actee: "anon user", Message: "Sending planet/{itemType}/{id} response", Severity: util.INFO})
}
// ActivateHandler is a handler for /planet
// @Title planetActivateHandler
// @Description Activates a scene
// @Accept plain
// @Param PL_API_KEY query string true "Planet Labs API Key"
// @Param itemType path string true "Planet Labs Item Type, e.g., rapideye or planetscope"
// @Param id path string true "Planet Labs image ID"
// @Success 200 {object} geojson.Feature
// @Failure 400 {object} string
// @Router /planet/activate/{itemType}/{id} [post]
type ActivateHandler struct {
Context Context
}
// NewActivateHandler creates a new handler using configuration
// from environment variables
func NewActivateHandler() ActivateHandler {
planetBaseURL := util.GetPlanetAPIURL()
tidesURL := util.GetTidesURL()
return ActivateHandler{
Context: Context{
BasePlanetURL: planetBaseURL,
BaseTidesURL: tidesURL,
},
}
}
// ServeHTTP implements the http.Handler interface for the ActivateHandler type
func (h ActivateHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
var (
err error
options MetadataOptions
response *http.Response
)
util.LogAudit(&h.Context, util.LogAuditInput{Actor: "anon user", Action: request.Method, Actee: request.URL.String(), Message: "Receiving /planet/activate/{itemType}/{id} request", Severity: util.INFO})
if util.Preflight(writer, request, &h.Context) {
return
}
vars := mux.Vars(request)
options.ID = vars["id"]
if options.ID == "" {
util.LogSimpleErr(&h.Context, noPlanetImageID, nil)
util.HTTPError(request, writer, &h.Context, noPlanetImageID, http.StatusBadRequest)
return
}
h.Context.PlanetKey = request.FormValue("PL_API_KEY")
if h.Context.PlanetKey == "" {
util.LogAlert(&h.Context, noPlanetKey)
util.HTTPError(request, writer, &h.Context, noPlanetKey, http.StatusBadRequest)
return
}
itemType := vars["itemType"]
switch itemType {
case "REOrthoTile", "rapideye":
options.ItemType = "REOrthoTile"
options.ImagerySource = rapidEye
case "PSOrthoTile", "planetscope":
options.ItemType = "PSOrthoTile"
options.ImagerySource = planetScope
case "Sentinel2L1C", "sentinel_planet":
options.ItemType = "Sentinel2L1C"
options.ImagerySource = sentinelFromPlanet
case "PSScene4Band":
// No op
case "sentinel_s3", "landsat":
message := fmt.Sprintf("The item type `%v` does not require activation", itemType)
util.LogSimpleErr(&h.Context, message, nil)
util.HTTPError(request, writer, &h.Context, message, http.StatusBadRequest)
return
default:
message := fmt.Sprintf("The item type value of %v is invalid", itemType)
util.LogSimpleErr(&h.Context, message, nil)
util.HTTPError(request, writer, &h.Context, message, http.StatusBadRequest)
return
}
if response, err = Activate(options, &h.Context); err == nil {
defer response.Body.Close()
writer.Header().Set("Content-Type", response.Header.Get("Content-Type"))
if (response.StatusCode >= 200) && (response.StatusCode < 300) {
bytes, _ := ioutil.ReadAll(response.Body)
writer.Write(bytes)
util.LogAudit(&h.Context, util.LogAuditInput{Actor: request.URL.String(), Action: request.Method + " response", Actee: "anon user", Message: "Sending planet/{itemType}/{id} response", Severity: util.INFO})
} else {
message := fmt.Sprintf("Failed to activate Planet Labs scene: " + response.Status)
err = util.LogSimpleErr(&h.Context, message, nil)
util.HTTPError(request, writer, &h.Context, err.Error(), response.StatusCode)
}
} else {
switch herr := err.(type) {
case util.HTTPErr:
util.HTTPError(request, writer, &h.Context, herr.Message, herr.Status)
default:
err = util.LogSimpleErr(&h.Context, "Failed to activate Planet Labs scene. ", err)
util.HTTPError(request, writer, &h.Context, err.Error(), 0)
}
}
}