-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathappprovider.go
438 lines (385 loc) · 13.3 KB
/
appprovider.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
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
// Copyright 2018-2021 CERN
//
// 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.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package appprovider
import (
"context"
"encoding/json"
"fmt"
"net/http"
"path"
appregistry "github.com/cs3org/go-cs3apis/cs3/app/registry/v1beta1"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/internal/http/services/datagateway"
"github.com/cs3org/reva/internal/http/services/ocmd"
"github.com/cs3org/reva/pkg/errtypes"
"github.com/cs3org/reva/pkg/rgrpc/status"
"github.com/cs3org/reva/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/pkg/rhttp"
"github.com/cs3org/reva/pkg/rhttp/global"
"github.com/cs3org/reva/pkg/rhttp/router"
"github.com/cs3org/reva/pkg/sharedconf"
"github.com/cs3org/reva/pkg/utils"
"github.com/cs3org/reva/pkg/utils/resourceid"
ua "github.com/mileusna/useragent"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func init() {
global.Register("appprovider", New)
}
// Config holds the config options that need to be passed down to all ocdav handlers
type Config struct {
Prefix string `mapstructure:"prefix"`
GatewaySvc string `mapstructure:"gatewaysvc"`
Insecure bool `mapstructure:"insecure"`
}
func (c *Config) init() {
if c.Prefix == "" {
c.Prefix = "app"
}
c.GatewaySvc = sharedconf.GetGatewaySVC(c.GatewaySvc)
}
type svc struct {
conf *Config
}
// New returns a new ocmd object
func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) {
conf := &Config{}
if err := mapstructure.Decode(m, conf); err != nil {
return nil, err
}
conf.init()
s := &svc{
conf: conf,
}
return s, nil
}
// Close performs cleanup.
func (s *svc) Close() error {
return nil
}
func (s *svc) Prefix() string {
return s.conf.Prefix
}
func (s *svc) Unprotected() []string {
return []string{"/list"}
}
func (s *svc) Handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var head string
head, r.URL.Path = router.ShiftPath(r.URL.Path)
switch r.Method {
case "POST":
switch head {
case "new":
s.handleNew(w, r)
case "open":
s.handleOpen(w, r)
default:
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "unsupported POST endpoint", nil)
}
case "GET":
switch head {
case "list":
s.handleList(w, r)
default:
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "unsupported GET endpoint", nil)
}
default:
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "unsupported method", nil)
}
})
}
func (s *svc) handleNew(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
client, err := pool.GetGatewayServiceClient(s.conf.GatewaySvc)
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error getting grpc gateway client", err)
return
}
if r.URL.Query().Get("template") != "" {
// TODO in the future we want to create a file out of the given template
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "Template not implemented",
errtypes.NotSupported("Templates are not yet supported"))
return
}
rootID := r.URL.Query().Get("file_root_id")
if rootID == "" {
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "Missing file root ID",
errtypes.UserRequired("Missing file root ID"))
return
}
rootRef := resourceid.OwnCloudResourceIDUnwrap(rootID)
if rootRef == nil {
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "Invalid file root ID",
errtypes.UserRequired("Invalid file root ID"))
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "Missing filename",
errtypes.UserRequired("Missing filename"))
return
}
dirPart, filePart := path.Split(filename)
if dirPart != "" || filePart != filename {
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "The filename must not contain a path segment",
errtypes.UserRequired("The filename must not contain a path segment"))
return
}
statRootReq := &provider.StatRequest{
Ref: &provider.Reference{
ResourceId: rootRef,
},
}
statRootRes, err := client.Stat(ctx, statRootReq)
if err != nil {
log.Error().Err(err).Msg("error sending a grpc stat request")
w.WriteHeader(http.StatusInternalServerError)
return
}
if statRootRes.Status.Code != rpc.Code_CODE_OK {
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "The file root ID is not accessible or does not exist",
errtypes.UserRequired("The file root ID is not accessible or does not exist"))
return
}
fileRef := &provider.Reference{
ResourceId: statRootRes.Info.Id,
Path: utils.MakeRelativePath(filename), // file by name inside the file root referenced by id
}
statFileReq := &provider.StatRequest{
Ref: fileRef,
}
statFileRes, err := client.Stat(ctx, statFileReq)
if err != nil {
log.Error().Err(err).Msg("error sending a grpc stat request")
w.WriteHeader(http.StatusInternalServerError)
return
}
if statFileRes.Status.Code != rpc.Code_CODE_NOT_FOUND {
if statFileRes.Status.Code == rpc.Code_CODE_OK {
ocmd.WriteError(w, r, ocmd.APIErrorInvalidParameter, "The file already exists",
errtypes.UserRequired("The file already exists"))
return
}
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error creating resource", status.NewErrorFromCode(statFileRes.Status.Code, "appprovider"))
return
}
// Create empty file via storageprovider
createReq := &provider.InitiateFileUploadRequest{
Ref: fileRef,
Opaque: &typespb.Opaque{
Map: map[string]*typespb.OpaqueEntry{
"Upload-Length": {
Decoder: "plain",
Value: []byte("0"),
},
},
},
}
// having a client.CreateFile() function would come in handy here...
createRes, err := client.InitiateFileUpload(ctx, createReq)
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error calling InitiateFileUpload", err)
return
}
if createRes.Status.Code != rpc.Code_CODE_OK {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error creating resource", status.NewErrorFromCode(createRes.Status.Code, "appprovider"))
return
}
// Do a HTTP PUT with an empty body
var ep, token string
for _, p := range createRes.Protocols {
if p.Protocol == "simple" {
ep, token = p.UploadEndpoint, p.Token
}
}
httpReq, err := rhttp.NewRequest(ctx, http.MethodPut, ep, nil)
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error executing PUT", err)
return
}
httpReq.Header.Set(datagateway.TokenTransportHeader, token)
httpRes, err := rhttp.GetHTTPClient(
rhttp.Context(ctx),
rhttp.Insecure(s.conf.Insecure),
).Do(httpReq)
if err != nil {
log.Error().Err(err).Msg("error doing PUT request to data service")
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error executing PUT", err)
return
}
defer httpRes.Body.Close()
if httpRes.StatusCode != http.StatusOK {
log.Error().Msg("PUT request to data server failed")
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error executing PUT",
errtypes.InternalError(fmt.Sprint(httpRes.StatusCode)))
return
}
// Stat the newly created file
statRes, ocmderr, err := statRef(ctx, *fileRef, client)
if err != nil {
log.Error().Err(err).Msg("error statting created file")
ocmd.WriteError(w, r, ocmderr, "Created file not found", errtypes.NotFound("Created file not found"))
return
}
js, err := json.Marshal(map[string]interface{}{"file_id": resourceid.OwnCloudResourceIDWrap(statRes.Id)})
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error marshalling JSON response", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err = w.Write(js); err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error writing JSON response", err)
return
}
}
func (s *svc) handleList(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
client, err := pool.GetGatewayServiceClient(s.conf.GatewaySvc)
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error getting grpc gateway client", err)
return
}
listRes, err := client.ListSupportedMimeTypes(ctx, &appregistry.ListSupportedMimeTypesRequest{})
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error listing supported mime types", err)
return
}
if listRes.Status.Code != rpc.Code_CODE_OK {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error listing supported mime types",
status.NewErrorFromCode(listRes.Status.Code, "appprovider"))
return
}
res := filterAppsByUserAgent(listRes.MimeTypes, r.UserAgent())
js, err := json.Marshal(map[string]interface{}{"mime-types": res})
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error marshalling JSON response", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err = w.Write(js); err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error writing JSON response", err)
return
}
}
func (s *svc) handleOpen(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
client, err := pool.GetGatewayServiceClient(s.conf.GatewaySvc)
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error getting grpc gateway client", err)
return
}
info, errCode, err := s.getStatInfo(ctx, r.URL.Query().Get("file_id"), client)
if err != nil {
ocmd.WriteError(w, r, errCode, "error statting file", err)
return
}
openReq := gateway.OpenInAppRequest{
Ref: &provider.Reference{ResourceId: info.Id},
ViewMode: getViewMode(info, r.URL.Query().Get("view_mode")),
App: r.URL.Query().Get("app_name"),
}
openRes, err := client.OpenInApp(ctx, &openReq)
if err != nil {
log.Error().Err(err).Msg("error calling OpenInApp")
ocmd.WriteError(w, r, ocmd.APIErrorServerError, err.Error(), err)
return
}
if openRes.Status.Code != rpc.Code_CODE_OK {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, openRes.Status.Message,
status.NewErrorFromCode(openRes.Status.Code, "error calling OpenInApp"))
return
}
js, err := json.Marshal(openRes.AppUrl)
if err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error marshalling JSON response", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err = w.Write(js); err != nil {
ocmd.WriteError(w, r, ocmd.APIErrorServerError, "error writing JSON response", err)
return
}
}
func filterAppsByUserAgent(mimeTypes []*appregistry.MimeTypeInfo, userAgent string) []*appregistry.MimeTypeInfo {
ua := ua.Parse(userAgent)
res := []*appregistry.MimeTypeInfo{}
for _, m := range mimeTypes {
apps := []*appregistry.ProviderInfo{}
for _, p := range m.AppProviders {
p.Address = "" // address is internal only and not needed in the client
// apps are called by name, so if it has no name it cannot be called and should not be advertised
// also filter Desktop-only apps if ua is not Desktop
if p.Name != "" && (ua.Desktop || !p.DesktopOnly) {
apps = append(apps, p)
}
}
if len(apps) > 0 {
m.AppProviders = apps
res = append(res, m)
}
}
return res
}
func (s *svc) getStatInfo(ctx context.Context, fileID string, client gateway.GatewayAPIClient) (*provider.ResourceInfo, ocmd.APIErrorCode, error) {
if fileID == "" {
return nil, ocmd.APIErrorInvalidParameter, errors.New("fileID parameter missing in request")
}
res := resourceid.OwnCloudResourceIDUnwrap(fileID)
if res != nil {
return nil, ocmd.APIErrorInvalidParameter, errors.New(fmt.Sprintf("fileID %s doesn't follow the required format", fileID))
}
return statRef(ctx, provider.Reference{ResourceId: res}, client)
}
func statRef(ctx context.Context, ref provider.Reference, client gateway.GatewayAPIClient) (*provider.ResourceInfo, ocmd.APIErrorCode, error) {
statReq := provider.StatRequest{Ref: &ref}
statRes, err := client.Stat(ctx, &statReq)
if err != nil {
return nil, ocmd.APIErrorServerError, err
}
if statRes.Status.Code != rpc.Code_CODE_OK {
return nil, ocmd.APIErrorServerError, status.NewErrorFromCode(statRes.Status.Code, "appprovider")
}
if statRes.Info.Type != provider.ResourceType_RESOURCE_TYPE_FILE {
return nil, ocmd.APIErrorServerError, errors.New("unsupported resource type")
}
return statRes.Info, ocmd.APIErrorCode(""), nil
}
func getViewMode(res *provider.ResourceInfo, vm string) gateway.OpenInAppRequest_ViewMode {
if vm != "" {
return utils.GetViewMode(vm)
}
var viewMode gateway.OpenInAppRequest_ViewMode
canEdit := res.PermissionSet.InitiateFileUpload
canView := res.PermissionSet.InitiateFileDownload
switch {
case canEdit && canView:
viewMode = gateway.OpenInAppRequest_VIEW_MODE_READ_WRITE
case canView:
viewMode = gateway.OpenInAppRequest_VIEW_MODE_READ_ONLY
default:
viewMode = gateway.OpenInAppRequest_VIEW_MODE_INVALID
}
return viewMode
}