-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathfileconnector.go
1406 lines (1260 loc) · 50.4 KB
/
fileconnector.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package connector
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"io"
"net/url"
"path"
"strings"
"time"
appproviderv1beta1 "github.com/cs3org/go-cs3apis/cs3/app/provider/v1beta1"
gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
"github.com/cs3org/reva/v2/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/v2/pkg/storagespace"
"github.com/cs3org/reva/v2/pkg/utils"
"github.com/google/uuid"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/config"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/connector/fileinfo"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/helpers"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/middleware"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/wopisrc"
"github.com/rs/zerolog"
)
const (
// WOPI Locks generally have a lock duration of 30 minutes and will be refreshed before expiration if needed
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/concepts#lock
lockDuration time.Duration = 30 * time.Minute
)
// FileConnectorService is the interface to implement the "Files"
// endpoint. Basically lock operations on the file plus the CheckFileInfo.
// All operations need a context containing a WOPI context and, optionally,
// a zerolog logger.
// Target file is within the WOPI context
type FileConnectorService interface {
// GetLock will return the lockID present in the target file.
GetLock(ctx context.Context) (*ConnectorResponse, error)
// Lock will lock the target file with the provided lockID. If the oldLockID
// is provided (not empty), the method will perform an unlockAndRelock
// operation (unlock the file with the oldLockID and immediately relock
// the file with the new lockID).
// The current lockID will be returned if a conflict happens
Lock(ctx context.Context, lockID, oldLockID string) (*ConnectorResponse, error)
// RefreshLock will extend the lock time 30 minutes. The current lockID
// needs to be provided.
// The current lockID will be returned if a conflict happens
RefreshLock(ctx context.Context, lockID string) (*ConnectorResponse, error)
// UnLock will unlock the target file. The current lockID needs to be
// provided.
// The current lockID will be returned if a conflict happens
UnLock(ctx context.Context, lockID string) (*ConnectorResponse, error)
// CheckFileInfo will return the file information of the target file
CheckFileInfo(ctx context.Context) (*ConnectorResponse, error)
// PutRelativeFileSuggested will create a new file based on the contents of the
// current file. Target is the filename that will be used for this
// new file.
// This implements the "suggested" code flow for the PutRelativeFile endpoint.
// Since we need to upload contents, it will be done through the provided
// The target must be UTF8-encoded.
// ContentConnectorService
PutRelativeFileSuggested(ctx context.Context, ccs ContentConnectorService, stream io.Reader, streamLength int64, target string) (*ConnectorResponse, error)
// PutRelativeFileRelative will create a new file based on the contents of the
// current file. Target is the filename that will be used for this
// new file.
// This implements the "relative" code flow for the PutRelativeFile endpoint.
// The required headers that could need to be sent through HTTP will also
// be returned if needed.
// The target must be UTF8-encoded.
// Since we need to upload contents, it will be done through the provided
// ContentConnectorService
PutRelativeFileRelative(ctx context.Context, ccs ContentConnectorService, stream io.Reader, streamLength int64, target string) (*ConnectorResponse, error)
// DeleteFile will delete the provided file in the context. Although
// not documented, a lockID can be used to try to delete a locked file
// assuming the lock matches.
// The current lockID will be returned if the file is locked.
DeleteFile(ctx context.Context, lockID string) (*ConnectorResponse, error)
// RenameFile will rename the provided file in the context to the requested
// filename. The filename must be UTF8-encoded.
// In case of conflict, this method will return the actual lockId in
// the file as second return value.
RenameFile(ctx context.Context, lockID, target string) (*ConnectorResponse, error)
}
// FileConnector implements the "File" endpoint.
// Currently, it handles file locks and getting the file info.
// Note that operations might return any kind of error, not just ConnectorError
type FileConnector struct {
gws pool.Selectable[gatewayv1beta1.GatewayAPIClient]
cfg *config.Config
}
// NewFileConnector creates a new file connector
func NewFileConnector(gws pool.Selectable[gatewayv1beta1.GatewayAPIClient], cfg *config.Config) *FileConnector {
return &FileConnector{
gws: gws,
cfg: cfg,
}
}
// GetLock returns a lock or an empty string if no lock exists
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/getlock
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// The lock ID applied to the file reference in the context will be returned
// (if any). An error will be returned if something goes wrong. The error
// could be a ConnectorError
func (f *FileConnector) GetLock(ctx context.Context) (*ConnectorResponse, error) {
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx)
req := &providerv1beta1.GetLockRequest{
Ref: wopiContext.FileReference,
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.GetLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("GetLock failed")
return nil, err
}
if resp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("GetLock failed with unexpected status")
// TODO: Should we be more strict? There could be more causes for the failure
return NewResponse(404), nil
}
lockID := ""
if resp.GetLock() != nil {
lockID = resp.GetLock().GetLockId()
}
// log the success at debug level
logger.Debug().
Str("LockID", lockID).
Msg("GetLock success")
return NewResponseWithLock(200, lockID), nil
}
// Lock returns a WOPI lock or performs an unlock and relock
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/lock
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/unlockandrelock
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// Lock the file reference contained in the context with the provided lockID.
// The oldLockID is only used for the "unlock and relock" operation. The "lock"
// operation doesn't use the oldLockID and needs to be empty in this case.
//
// For the "lock" operation, if the operation is successful, an empty lock id
// will be returned without any error. In case of conflict, the current lock
// id will be returned along with a 409 ConnectorError. For any other error,
// the method will return an empty lock id.
//
// For the "unlock and relock" operation, the behavior will be the same.
//
// On success, the mtime of the file will be returned in the X-Wopi-Version header.
func (f *FileConnector) Lock(ctx context.Context, lockID, oldLockID string) (*ConnectorResponse, error) {
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx).With().
Str("RequestedLockID", lockID).
Str("RequestedOldLockID", oldLockID).
Logger()
logger.Debug().Msg("Lock: start")
if lockID == "" {
logger.Error().Msg("Lock failed due to empty lockID")
return NewResponse(400), nil
}
var setOrRefreshStatus *rpcv1beta1.Status
if oldLockID == "" {
// If the oldLockID is empty, this is a "LOCK" request
logger.Debug().Msg("Lock: this is a SetLock request")
req := &providerv1beta1.SetLockRequest{
Ref: wopiContext.FileReference,
Lock: &providerv1beta1.Lock{
LockId: lockID,
AppName: f.cfg.App.LockName + "." + f.cfg.App.Name,
Type: providerv1beta1.LockType_LOCK_TYPE_WRITE,
Expiration: &typesv1beta1.Timestamp{
Seconds: uint64(time.Now().Add(lockDuration).Unix()),
},
},
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.SetLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("SetLock failed")
return nil, err
}
setOrRefreshStatus = resp.GetStatus()
} else {
// If the oldLockID isn't empty, this is a "UnlockAndRelock" request. We'll
// do a "RefreshLock" in reva and provide the old lock
logger.Debug().Msg("Lock: this is a RefreshLock request")
req := &providerv1beta1.RefreshLockRequest{
Ref: wopiContext.FileReference,
Lock: &providerv1beta1.Lock{
LockId: lockID,
AppName: f.cfg.App.LockName + "." + f.cfg.App.Name,
Type: providerv1beta1.LockType_LOCK_TYPE_WRITE,
Expiration: &typesv1beta1.Timestamp{
Seconds: uint64(time.Now().Add(lockDuration).Unix()),
},
},
ExistingLockId: oldLockID,
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.RefreshLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("UnlockAndRefresh failed")
return nil, err
}
setOrRefreshStatus = resp.GetStatus()
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
statResp, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
Ref: wopiContext.FileReference,
})
if err != nil {
logger.Error().Err(err).Msg("Lock failed trying to get the file info")
return nil, err
}
if statResp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", statResp.GetStatus().GetCode().String()).
Str("StatusMsg", statResp.GetStatus().GetMessage()).
Msg("Lock failed trying to get the file info with unexpected status")
return NewResponse(500), nil
}
// we're checking the status of either the "SetLock" or "RefreshLock" operations
switch setOrRefreshStatus.GetCode() {
case rpcv1beta1.Code_CODE_OK:
logger.Debug().Msg("SetLock successful")
return NewResponseWithVersion(statResp.GetInfo().GetMtime()), nil
case rpcv1beta1.Code_CODE_FAILED_PRECONDITION, rpcv1beta1.Code_CODE_ABORTED:
// Code_CODE_FAILED_PRECONDITION -> Lock operation mismatched lock
// Code_CODE_ABORTED -> UnlockAndRelock operation mismatched lock
// In both cases, we need to get the current lock to return it in a
// 409 response if needed
req := &providerv1beta1.GetLockRequest{
Ref: wopiContext.FileReference,
}
gwc, err = f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.GetLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("SetLock failed, fallback to GetLock failed too")
return nil, err
}
if resp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("SetLock failed, fallback to GetLock failed with unexpected status")
}
if resp.GetLock() != nil {
if resp.GetLock().GetLockId() != lockID {
// lockId is different -> return 409 with the current lockId
logger.Warn().
Str("LockID", resp.GetLock().GetLockId()).
Msg("SetLock conflict")
return NewResponseLockConflict(resp.GetLock().GetLockId(), "Conflicting LockID"), nil
}
// TODO: according to the spec we need to treat this as a RefreshLock
// There was a problem with the lock, but the file has the same lockId now.
// This should never happen unless there are race conditions.
// Since the lockId matches now, we'll assume success for now.
// As said in the todo, we probably should send a "RefreshLock" request here.
logger.Warn().
Str("LockID", resp.GetLock().GetLockId()).
Msg("SetLock lock refreshed instead")
return NewResponseWithVersion(statResp.GetInfo().GetMtime()), nil
}
logger.Error().Msg("SetLock failed and could not refresh")
return NewResponse(500), nil
case rpcv1beta1.Code_CODE_NOT_FOUND:
logger.Error().Msg("SetLock failed, file not found")
return NewResponse(404), nil
default:
logger.Error().
Str("StatusCode", setOrRefreshStatus.GetCode().String()).
Str("StatusMsg", setOrRefreshStatus.GetMessage()).
Msg("SetLock failed with unexpected status")
return NewResponse(500), nil
}
}
// RefreshLock refreshes a provided lock for 30 minutes
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/refreshlock
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// If the operation is successful, an empty lock id will be returned without
// any error. In case of conflict, the current lock id will be returned
// along with a 409 ConnectorError. For any other error, the method will
// return an empty lock id.
// The conflict happens if the provided lockID doesn't match the one actually
// applied in the target file.
//
// On success, the mtime of the file will be returned in the X-Wopi-Version header.
func (f *FileConnector) RefreshLock(ctx context.Context, lockID string) (*ConnectorResponse, error) {
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx).With().
Str("RequestedLockID", lockID).
Logger()
logger.Debug().Msg("RefreshLock: start")
if lockID == "" {
logger.Error().Msg("RefreshLock failed due to empty lockID")
return NewResponse(400), nil
}
req := &providerv1beta1.RefreshLockRequest{
Ref: wopiContext.FileReference,
Lock: &providerv1beta1.Lock{
LockId: lockID,
AppName: f.cfg.App.LockName + "." + f.cfg.App.Name,
Type: providerv1beta1.LockType_LOCK_TYPE_WRITE,
Expiration: &typesv1beta1.Timestamp{
Seconds: uint64(time.Now().Add(lockDuration).Unix()),
},
},
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.RefreshLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("RefreshLock failed")
return nil, err
}
gwc, err = f.gws.Next()
if err != nil {
return nil, err
}
statResp, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
Ref: wopiContext.FileReference,
})
if err != nil {
logger.Error().Err(err).Msg("RefreshLock failed trying to get the file info")
return nil, err
}
if statResp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", statResp.GetStatus().GetCode().String()).
Str("StatusMsg", statResp.GetStatus().GetMessage()).
Msg("RefreshLock failed trying to get the file info with unexpected status")
return NewResponse(500), nil
}
switch resp.GetStatus().GetCode() {
case rpcv1beta1.Code_CODE_OK:
logger.Debug().Msg("RefreshLock successful")
// The current lock should not be returned in the headers on success
// https://learn.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/refreshlock#response-headers
return NewResponseWithVersion(statResp.GetInfo().GetMtime()), nil
case rpcv1beta1.Code_CODE_NOT_FOUND:
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("RefreshLock failed, file reference not found")
return NewResponse(404), nil
case rpcv1beta1.Code_CODE_ABORTED:
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("RefreshLock failed, lock mismatch")
// Either the file is unlocked or there is no lock
// We need to return 409 with the current lock
req := &providerv1beta1.GetLockRequest{
Ref: wopiContext.FileReference,
}
gwc, err = f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.GetLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("RefreshLock failed trying to get the current lock")
return nil, err
}
if resp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("RefreshLock failed, tried to get the current lock failed with unexpected status")
return NewResponse(500), nil
}
if resp.GetLock() == nil {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("RefreshLock failed, no lock on file")
return NewResponseLockConflict("", "No lock on file"), nil
} else {
// lock is different than the one requested, otherwise we wouldn't reached this point
logger.Error().
Str("LockID", resp.GetLock().GetLockId()).
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("RefreshLock failed, lock mismatch")
return NewResponseLockConflict(resp.GetLock().GetLockId(), "Lock mismatch"), nil
}
default:
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("RefreshLock failed with unexpected status")
return NewResponse(500), nil
}
}
// UnLock removes a given lock from a file
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/unlock
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// If the operation is successful, an empty lock id will be returned without
// any error. In case of conflict, the current lock id will be returned
// along with a 409 ConnectorError. For any other error, the method will
// return an empty lock id.
// The conflict happens if the provided lockID doesn't match the one actually
// applied in the target file.
//
// On success, the mtime of the file will be returned in the X-Wopi-Version header.
func (f *FileConnector) UnLock(ctx context.Context, lockID string) (*ConnectorResponse, error) {
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx).With().
Str("RequestedLockID", lockID).
Logger()
logger.Debug().Msg("UnLock: start")
if lockID == "" {
logger.Error().Msg("Unlock failed due to empty lockID")
return NewResponse(400), nil
}
req := &providerv1beta1.UnlockRequest{
Ref: wopiContext.FileReference,
Lock: &providerv1beta1.Lock{
LockId: lockID,
AppName: f.cfg.App.LockName + "." + f.cfg.App.Name,
},
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.Unlock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("Unlock failed")
return nil, err
}
gwc, err = f.gws.Next()
if err != nil {
return nil, err
}
statResp, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
Ref: wopiContext.FileReference,
})
if err != nil {
logger.Error().Err(err).Msg("Unlock failed trying to get the file info")
return nil, err
}
if statResp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", statResp.GetStatus().GetCode().String()).
Str("StatusMsg", statResp.GetStatus().GetMessage()).
Msg("Unlock failed trying to get the file info with unexpected status")
return NewResponse(500), nil
}
switch resp.GetStatus().GetCode() {
case rpcv1beta1.Code_CODE_OK:
logger.Debug().Msg("Unlock successful")
return NewResponseWithVersion(statResp.GetInfo().GetMtime()), nil
case rpcv1beta1.Code_CODE_ABORTED:
// File isn't locked. Need to return 409 with empty lock
logger.Error().Err(err).Msg("Unlock failed, file isn't locked")
return NewResponseLockConflict("", "File isn't locked"), nil
case rpcv1beta1.Code_CODE_LOCKED:
// We need to return 409 with the current lock
req := &providerv1beta1.GetLockRequest{
Ref: wopiContext.FileReference,
}
gwc, err = f.gws.Next()
if err != nil {
return nil, err
}
resp, err := gwc.GetLock(ctx, req)
if err != nil {
logger.Error().Err(err).Msg("Unlock failed trying to get the current lock")
return nil, err
}
if resp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("Unlock failed, tried to get the current lock failed with unexpected status")
return NewResponse(500), nil
}
var outLockId string
if resp.GetLock() == nil {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("Unlock failed, no lock on file")
outLockId = ""
} else {
// lock is different than the one requested, otherwise we wouldn't reached this point
logger.Error().
Str("LockID", resp.GetLock().GetLockId()).
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("Unlock failed, lock mismatch")
outLockId = resp.GetLock().GetLockId()
}
return NewResponseLockConflict(outLockId, "Lock mismatch"), nil
default:
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("Unlock failed with unexpected status")
return NewResponse(500), nil
}
}
// PutRelativeFileSuggested upload a file using the suggested target name
// https://learn.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/putrelativefile
//
// The PutRelativeFile have 2 variants based on the "X-WOPI-SuggestedTarget"
// and "X-WOPI-RelativeTarget" headers. This method only implements the first,
// so this method must be used only if the "X-WOPI-SuggestedTarget" is present.
//
// The "target" filename must be UTF8-encoded. The conversion between UTF7 and
// UTF8 must happen outside this function.
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// Since the method involves uploading a file to a location, it will use the
// provided ContentConnectorService to upload the stream. Note that the
// associated wopicontext is modified in order to point to the right location
// before the upload (it shouldn't matter because we'll work on a copy).
//
// As per documentation, this method will try to upload the provided stream
// using the suggested name. If the upload fails, we'll try using a different
// name. This new name will be generated by prefixing a random string to the
// suggested name.
// Since the upload won't use any lock, the upload will fail if the target file
// already exists and it isn't empty. This means that, this method can only
// generate new files.
func (f *FileConnector) PutRelativeFileSuggested(ctx context.Context, ccs ContentConnectorService, stream io.Reader, streamLength int64, target string) (*ConnectorResponse, error) {
// assume the target is a full name
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx).With().
Str("PutTarget", target).
Logger()
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
// stat the current file in order to get the reference of the parent folder
oldStatRes, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
Ref: wopiContext.FileReference,
})
if err != nil {
logger.Error().Err(err).Msg("PutRelativeFileSuggested: stat failed")
return nil, err
}
if oldStatRes.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", oldStatRes.GetStatus().GetCode().String()).
Str("StatusMsg", oldStatRes.GetStatus().GetMessage()).
Msg("PutRelativeFileSuggested: stat failed with unexpected status")
return NewResponse(500), nil
}
if strings.HasPrefix(target, ".") {
// the target is an extension, so we need to use the original
// name with the modified extension
oldStatPath := oldStatRes.GetInfo().GetPath()
ext := path.Ext(oldStatPath)
target = strings.TrimSuffix(path.Base(oldStatPath), ext) + target
}
finalTarget := target
newLogger := logger
for isDone := false; !isDone; {
targetPath := utils.MakeRelativePath(finalTarget)
// need to change the file reference of the wopicontext to point to the new path
wopiContext.FileReference = &providerv1beta1.Reference{
ResourceId: oldStatRes.GetInfo().GetParentId(),
Path: targetPath,
}
// create a new context for the modified wopicontext
newLogger := logger.With().Str("NewFileReference", wopiContext.FileReference.String()).Logger()
newCtx := middleware.WopiContextToCtx(newLogger.WithContext(ctx), wopiContext)
// try to put the file. It mustn't return a 400 or 409
putResponse, err := ccs.PutFile(newCtx, stream, streamLength, "")
if err != nil {
newLogger.Error().Err(err).Msg("PutRelativeFileSuggested: put file failed") // fails here
return nil, err
}
switch putResponse.Status {
case 200:
// if the put is successful, exit the loop and move on
isDone = true
logger = newLogger
case 409:
// if conflict generate a different name and retry.
// this should happen only once
actualFilename, _ := f.extractFilenameAndPrefix(target)
finalTarget = f.generatePrefix() + " " + actualFilename
default:
// TODO: code 400 might happen, what to do?
// in other cases, just return the error
newLogger.Error().Msg("PutRelativeFileSuggested: put file failed with unhandled status")
return NewResponse(500), nil
}
}
// adjust the wopi file reference to use only the resource id without path
if err := f.adjustWopiReference(ctx, &wopiContext, newLogger); err != nil {
return nil, err
}
wopiSrcURL, err := f.generateWOPISrc(wopiContext, newLogger)
if err != nil {
logger.Error().Err(err).Msg("PutRelativeFileSuggested: error generating the WOPISrc parameter")
return nil, err
}
logger.Debug().
Str("FinalReference", wopiContext.FileReference.String()).
Msg("PutRelativeFileSuggested: success")
return NewResponseSuccessBodyNameUrl(finalTarget, wopiSrcURL.String()), nil
}
// PutRelativeFileRelative upload a file using the provided target name
// https://learn.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/putrelativefile
//
// The PutRelativeFile have 2 variants based on the "X-WOPI-SuggestedTarget"
// and "X-WOPI-RelativeTarget" headers. This method only implements the second,
// so this method must be used only if the "X-WOPI-RelativeTarget" is present.
//
// The "target" filename must be UTF8-encoded. The conversion between UTF7 and
// UTF8 must happen outside this function.
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// Since the method involves uploading a file to a location, it will use the
// provided ContentConnectorService to upload the stream. Note that the
// associated wopicontext is modified in order to point to the right location
// before the upload (it shouldn't matter because we'll work on a copy).
//
// As per documentation, this method will try to upload the provided stream
// using the provided name. The filename won't be changed.
// Since the upload won't use any lock, the upload will fail if the target file
// already exists and it isn't empty. This means that, this method can only
// generate new files.
func (f *FileConnector) PutRelativeFileRelative(ctx context.Context, ccs ContentConnectorService, stream io.Reader, streamLength int64, target string) (*ConnectorResponse, error) {
// assume the target is a full name
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx).With().
Str("PutTarget", target).
Logger()
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
// stat the current file in order to get the reference of the parent folder
oldStatRes, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
Ref: wopiContext.FileReference,
})
if err != nil {
logger.Error().Err(err).Msg("PutRelativeFileRelative: stat failed")
return nil, err
}
if oldStatRes.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", oldStatRes.GetStatus().GetCode().String()).
Str("StatusMsg", oldStatRes.GetStatus().GetMessage()).
Msg("PutRelativeFileRelative: stat failed with unexpected status")
return NewResponse(500), nil
}
targetPath := utils.MakeRelativePath(target)
// need to change the file reference of the wopicontext to point to the new path
wopiContext.FileReference = &providerv1beta1.Reference{
ResourceId: oldStatRes.GetInfo().GetParentId(),
Path: targetPath,
}
// create a new context for the modified wopicontext
newLogger := logger.With().Str("NewFileReference", wopiContext.FileReference.String()).Logger()
newCtx := middleware.WopiContextToCtx(newLogger.WithContext(ctx), wopiContext)
// try to put the file
putResponse, err := ccs.PutFile(newCtx, stream, streamLength, "")
if err != nil {
newLogger.Error().Err(err).Msg("PutRelativeFileRelative: put file failed") // or here
return nil, err
}
lockID := ""
if putResponse.Headers != nil {
lockID = putResponse.Headers[HeaderWopiLock]
}
switch putResponse.Status {
case 200: // success case, so don't do anything
case 409:
if err := f.adjustWopiReference(ctx, &wopiContext, newLogger); err != nil {
return nil, err
}
// if conflict generate a different name and retry.
// this should happen only once
wopiSrcURL, err2 := f.generateWOPISrc(wopiContext, newLogger)
if err2 != nil {
newLogger.Error().
Err(err2).
Str("LockID", lockID).
Msg("PutRelativeFileRelative: error generating the WOPISrc parameter for conflict response")
return nil, err2
}
actualFilename, _ := f.extractFilenameAndPrefix(target)
finalTarget := f.generatePrefix() + " " + actualFilename
newLogger.Error().
Str("LockID", lockID).
Msg("PutRelativeFileRelative: error conflict")
// need to build the response ourselves
return &ConnectorResponse{
Status: 409,
Headers: map[string]string{
HeaderWopiValidRT: finalTarget,
HeaderWopiLock: lockID,
HeaderWopiLockFailureReason: "Lock Conflict",
},
Body: map[string]interface{}{
"Name": target,
"Url": wopiSrcURL.String(),
},
}, nil
default:
newLogger.Error().
Str("LockID", lockID).
Msg("PutRelativeFileRelative: put file failed with unhandled status")
return nil, NewConnectorError(putResponse.Status, "put file failed with unhandled status")
}
if err := f.adjustWopiReference(ctx, &wopiContext, newLogger); err != nil {
return nil, err
}
wopiSrcURL, err := f.generateWOPISrc(wopiContext, newLogger)
if err != nil {
newLogger.Error().Err(err).Msg("PutRelativeFileRelative: error generating the WOPISrc parameter")
return nil, err
}
newLogger.Debug().Msg("PutRelativeFileRelative: success")
return NewResponseSuccessBodyNameUrl(target, wopiSrcURL.String()), nil
}
// DeleteFile will delete the requested file
// https://learn.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/deletefile
//
// The lock isn't part of the documentation, but it might be possible to
// delete a file as long as you have the lock. In addition, we'll need to
// return the lock if there is a conflict.
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// Note that this method isn't required and it's likely used just for the
// WOPI validator
func (f *FileConnector) DeleteFile(ctx context.Context, lockID string) (*ConnectorResponse, error) {
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}
logger := zerolog.Ctx(ctx).With().
Str("RequestedLockID", lockID).
Logger()
var deleteRes *providerv1beta1.DeleteResponse
deleteReq := &providerv1beta1.DeleteRequest{
Ref: wopiContext.FileReference,
LockId: lockID,
}
// we'll retry the request after a while if we get a "TOO_EARLY" code
for retries := 0; deleteRes == nil || deleteRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_TOO_EARLY; retries++ {
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
deleteRes, err = gwc.Delete(ctx, deleteReq)
if err != nil {
logger.Error().Err(err).Msg("DeleteFile: stat failed")
return nil, err
}
if deleteRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_TOO_EARLY {
// starting from 20ms, double the waiting time for each retry
// capping at 5 secs
var waitingTime time.Duration
waitingTime = (20 * time.Millisecond) << retries
if waitingTime.Seconds() > 5 {
waitingTime = 5 * time.Second
}
logger.Warn().
Str("StatusCode", deleteRes.GetStatus().GetCode().String()).
Str("StatusMsg", deleteRes.GetStatus().GetMessage()).
Dur("WaitingTime", waitingTime).
Int("Retries", retries).
Msg("DeleteFile: file isn't ready yet. Retrying")
time.Sleep(waitingTime)
}
}
if deleteRes.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", deleteRes.GetStatus().GetCode().String()).
Str("StatusMsg", deleteRes.GetStatus().GetMessage()).
Msg("DeleteFile: delete failed with unexpected status")
if deleteRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_NOT_FOUND {
// don't bother to check for locks of a missing file
logger.Error().Msg("DeleteFile: tried to delete a missing file")
return NewResponse(404), nil
}
// check if the file is locked to return a proper lockID
req := &providerv1beta1.GetLockRequest{
Ref: wopiContext.FileReference,
}
gwc, err := f.gws.Next()
if err != nil {
return nil, err
}
resp, err2 := gwc.GetLock(ctx, req)
if err2 != nil {
logger.Error().Err(err2).Msg("DeleteFile: GetLock failed")
return nil, err2
}
if resp.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
logger.Error().
Str("StatusCode", resp.GetStatus().GetCode().String()).
Str("StatusMsg", resp.GetStatus().GetMessage()).
Msg("DeleteFile: GetLock failed with unexpected status")
return NewResponse(500), nil
}
if resp.GetLock() != nil {
logger.Error().
Str("LockID", resp.GetLock().GetLockId()).
Msg("DeleteFile: file is locked")
return NewResponseLockConflict(resp.GetLock().GetLockId(), "File is locked"), nil
} else {
// return the original error since the file isn't locked
logger.Error().Msg("DeleteFile: delete failed on unlocked file")
return NewResponse(500), nil
}
}
logger.Debug().Msg("DeleteFile: success")
return NewResponse(200), nil
}
// RenameFile will rename the requested file
// https://learn.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/renamefile
//
// The "target" filename must be UTF8-encoded. The conversion between UTF7 and
// UTF8 must happen outside this function.
//
// The context MUST have a WOPI context, otherwise an error will be returned.
// You can pass a pre-configured zerologger instance through the context that
// will be used to log messages.
//
// The method will return the final target name as first return value (target
// is just a suggestion, so it could have changed) and the actual lockId in
// case of conflict as second return value, otherwise the returned lockId will
// be empty.
func (f *FileConnector) RenameFile(ctx context.Context, lockID, target string) (*ConnectorResponse, error) {
wopiContext, err := middleware.WopiContextFromCtx(ctx)
if err != nil {
return nil, err
}