-
Notifications
You must be signed in to change notification settings - Fork 1
/
Image.go
294 lines (254 loc) · 9.27 KB
/
Image.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
// Licensed to NASA JPL under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. NASA JPL licenses this file to you 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 endpoints
import (
"bytes"
"context"
"errors"
"fmt"
"image"
"image/color"
"net/http"
"path"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/pixlise/core/v4/api/dbCollections"
"github.com/pixlise/core/v4/api/filepaths"
apiRouter "github.com/pixlise/core/v4/api/router"
"github.com/pixlise/core/v4/api/services"
"github.com/pixlise/core/v4/api/ws/wsHelpers"
"github.com/pixlise/core/v4/core/errorwithstatus"
"github.com/pixlise/core/v4/core/imageedit"
protos "github.com/pixlise/core/v4/generated-protos"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
const ScanIdentifier = "scan"
const FileNameIdentifier = "filename"
func getBoolValue(str string) (bool, error) {
if len(str) <= 0 {
return false, nil
}
switch str {
case "true":
return true, nil
case "false":
return false, nil
default:
return false, fmt.Errorf("invalid boolean value: %v", str)
}
}
func addFileNameSuffix(name string, suffix string) string {
ext := path.Ext(name)
name = name[0 : len(name)-len(ext)]
return name + suffix + ext
}
func GetImage(params apiRouter.ApiHandlerStreamParams) (*s3.GetObjectOutput, string, string, string, int, error) {
// Path elements
scanID := params.PathParams[ScanIdentifier]
requestedFileName := path.Join(scanID, params.PathParams[FileNameIdentifier])
// Check access to each associated scan. The user should already have a web socket open by this point, so we can
// look to see if there is a cached copy of their user group membership. If we don't find one, we stop
memberOfGroupIds, isMemberOfNoGroups := wsHelpers.GetCachedUserGroupMembership(params.UserInfo.UserID)
viewerOfGroupIds, isViewerOfNoGroups := wsHelpers.GetCachedUserGroupViewership(params.UserInfo.UserID)
if !isMemberOfNoGroups && !isViewerOfNoGroups {
// User is probably not logged in
return nil, "", "", "", 0, errorwithstatus.MakeBadRequestError(errors.New("User has no group membership, can't determine permissions"))
}
// Now read the DB record for the image, so we can determine what scans it's associated with
ctx := context.TODO()
coll := params.Svcs.MongoDB.Collection(dbCollections.ImagesName)
filter := bson.M{"_id": requestedFileName}
imageDBResult := coll.FindOne(ctx, filter)
if imageDBResult.Err() != nil {
// This doesn't look good...
if imageDBResult.Err() == mongo.ErrNoDocuments {
return nil, "", "", "", 0, errorwithstatus.MakeNotFoundError(requestedFileName)
}
return nil, "", "", "", 0, imageDBResult.Err()
}
dbImage := protos.ScanImage{}
err := imageDBResult.Decode(&dbImage)
if err != nil {
return nil, "", "", "", 0, err
}
for _, scanId := range dbImage.AssociatedScanIds {
_, err := wsHelpers.CheckObjectAccessForUser(false, scanId, protos.ObjectType_OT_SCAN, params.UserInfo.UserID, memberOfGroupIds, viewerOfGroupIds, params.Svcs.MongoDB)
if err != nil {
return nil, "", "", "", 0, err
}
}
// We're still here, so we have access! Check query params for any modifiers
finalFileName := requestedFileName
showLocations, err := getBoolValue(params.PathParams["with-locations"])
if err != nil {
return nil, "", "", "", 0, err
} else if showLocations {
finalFileName = addFileNameSuffix(finalFileName, "-withloc")
}
var minWidthPx = 0
if minWStr, ok := params.PathParams["minwidth"]; ok {
// We DO have a value set for this, read it
minWidthPx, err = strconv.Atoi(minWStr)
if err != nil {
return nil, "", "", "", 0, err
} else {
// We got a min width, round it to our step size
if minWidthPx < 0 {
minWidthPx = 0
}
step := minWidthPx / imageSizeStepPx
if step <= 0 {
step = 1
}
minWidthPx = imageSizeStepPx * step
// Only do this if we're not scaling it up!
if minWidthPx < int(dbImage.Width) {
finalFileName = addFileNameSuffix(finalFileName, fmt.Sprintf("-width%v", minWidthPx))
} else {
minWidthPx = 0 // pretend user didn't ask to scale it
}
}
}
statuscode := 200
// Load from dataset directory unless custom loading is requested, where we look up the file in the manual bucket
imgBucket := params.Svcs.Config.DatasetsBucket
// Check if the file exists, as we may be able to generate a version of the underlying file to satisfy the request
var s3Path string
if minWidthPx > 0 || showLocations {
s3Path = filepaths.GetImageCacheFilePath(finalFileName)
} else {
s3Path = filepaths.GetImageFilePath(finalFileName)
}
_, err = params.Svcs.S3.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(imgBucket),
Key: aws.String(s3Path),
})
if err != nil {
if minWidthPx > 0 || showLocations {
// If the file doesn't exist, check if the base file name exists, because we may just need to generate
// a modified version of it
genS3Path := filepaths.GetImageFilePath(requestedFileName)
// Original file exists, generate this modified copy and cache it back in S3 for the rest of this
// function to find!
err = generateImageVersion(genS3Path, minWidthPx, showLocations, s3Path, params.Svcs)
}
if err != nil {
// Failed at this, stop here
return nil, "", "", "", 0, err
}
}
if params.Headers != nil && params.Headers.Get("If-None-Match") != "" {
head, err := params.Svcs.S3.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(imgBucket),
Key: aws.String(s3Path),
})
if err == nil {
if head != nil && head.ETag != nil {
header := params.Headers.Get("If-None-Match")
if header != "" && strings.Contains(header, *head.ETag) {
statuscode = http.StatusNotModified
return nil, requestedFileName, *head.ETag, head.LastModified.String(), statuscode, nil
}
}
}
}
if params.Headers != nil && params.Headers.Get("If-Modified-Since") != "" {
head, err := params.Svcs.S3.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(imgBucket),
Key: aws.String(s3Path),
})
if err == nil {
if head != nil && head.LastModified != nil {
header := params.Headers.Get("If-Modified-Since")
if header != "" && strings.Contains(header, head.LastModified.String()) {
statuscode = http.StatusNotModified
return nil, requestedFileName, *head.ETag, head.LastModified.String(), statuscode, nil
}
}
}
}
obj := &s3.GetObjectInput{
Bucket: aws.String(imgBucket),
Key: aws.String(s3Path),
}
result, err := params.Svcs.S3.GetObject(obj)
var etag = ""
var lm = time.Time{}
if result != nil && result.ETag != nil {
params.Svcs.Log.Debugf("ETAG for cache: %s, s3://%v/%v", *result.ETag, imgBucket, s3Path)
etag = *result.ETag
}
if result != nil && result.LastModified != nil {
lm = *result.LastModified
params.Svcs.Log.Debugf("Last Modified for cache: %v, s3://%v/%v", lm, imgBucket, s3Path)
}
return result, requestedFileName, etag, lm.String(), 0, err
}
const imageSizeStepPx = 200
func generateImageVersion(s3Path string, minWidthPx int, showLocations bool, finalFilePath string, svcs *services.APIServices) error {
if minWidthPx <= 0 {
return fmt.Errorf("generateImageVersion minWidthPx too small: %v", minWidthPx)
}
imgBytes, err := svcs.FS.ReadObject(svcs.Config.DatasetsBucket, s3Path)
if err != nil {
return err
}
img, imgFormat, err := image.Decode(bytes.NewReader(imgBytes))
if err != nil {
return err
}
// Apply the mods
if showLocations {
// Read locations from DB for this image
ctx := context.TODO()
coll := svcs.MongoDB.Collection(dbCollections.ImageBeamLocationsName)
filter := bson.M{"_id": path.Base(s3Path)}
result := coll.FindOne(ctx, filter)
if result.Err() != nil {
// We don't stop here, we just log the error and allow the image generation to complete
svcs.Log.Errorf("Failed to load beam locations for marking on image %v. Error was: %v", s3Path, result.Err())
} else {
locs := protos.ImageLocations{}
err = result.Decode(&locs)
if err != nil {
svcs.Log.Errorf("Failed to decode loaded beam locations for marking on image %v. Error was: %v", s3Path, result.Err())
} else {
// Merge all coordinates
coords := []*protos.Coordinate2D{}
for _, coordsForScan := range locs.LocationPerScan {
coords = append(coords, coordsForScan.Locations...)
}
// Mark them on the image
img = imageedit.MarkLocations(img, coords, color.Black, nil)
}
}
}
if minWidthPx > 0 {
img = imageedit.ScaleImage(img, minWidthPx)
}
// Now we're done, read the bytes out in the right format
imgBytesOut, err := imageedit.GetImageBytes(img, imgFormat)
if err != nil {
return err
}
// Write the final image to final cached destination
return svcs.FS.WriteObject(svcs.Config.DatasetsBucket, finalFilePath, imgBytesOut)
}