/
webapi.go
1095 lines (1018 loc) · 33.4 KB
/
webapi.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 seafile
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"github.com/rclone/rclone/backend/seafile/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
// Start of the API URLs
const (
APIv20 = "api2/repos/"
APIv21 = "api/v2.1/repos/"
)
// Errors specific to seafile fs
var (
ErrorInternalDuringUpload = errors.New("internal server error during file upload")
)
// ==================== Seafile API ====================
func (f *Fs) getAuthorizationToken(ctx context.Context) (string, error) {
return getAuthorizationToken(ctx, f.srv, f.opt.User, f.opt.Password, "")
}
// getAuthorizationToken can be called outside of an fs (during configuration of the remote to get the authentication token)
// it's doing a single call (no pacer involved)
func getAuthorizationToken(ctx context.Context, srv *rest.Client, user, password, oneTimeCode string) (string, error) {
// API Documentation
// https://download.seafile.com/published/web-api/home.md#user-content-Quick%20Start
opts := rest.Opts{
Method: "POST",
Path: "api2/auth-token/",
ExtraHeaders: map[string]string{"Authorization": ""}, // unset the Authorization for this request
IgnoreStatus: true, // so we can load the error messages back into result
}
// 2FA
if oneTimeCode != "" {
opts.ExtraHeaders["X-SEAFILE-OTP"] = oneTimeCode
}
request := api.AuthenticationRequest{
Username: user,
Password: password,
}
result := api.AuthenticationResult{}
_, err := srv.CallJSON(ctx, &opts, &request, &result)
if err != nil {
// This is only going to be http errors here
return "", fmt.Errorf("failed to authenticate: %w", err)
}
if result.Errors != nil && len(result.Errors) > 0 {
return "", errors.New(strings.Join(result.Errors, ", "))
}
if result.Token == "" {
// No error in "non_field_errors" field but still empty token
return "", errors.New("failed to authenticate")
}
return result.Token, nil
}
func (f *Fs) getServerInfo(ctx context.Context) (account *api.ServerInfo, err error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/server-info.md#user-content-Get%20Server%20Information
opts := rest.Opts{
Method: "GET",
Path: "api2/server-info/",
}
result := api.ServerInfo{}
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to get server info: %w", err)
}
return &result, nil
}
func (f *Fs) getUserAccountInfo(ctx context.Context) (account *api.AccountInfo, err error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/account.md#user-content-Check%20Account%20Info
opts := rest.Opts{
Method: "GET",
Path: "api2/account/info/",
}
result := api.AccountInfo{}
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to get account info: %w", err)
}
return &result, nil
}
func (f *Fs) getLibraries(ctx context.Context) ([]api.Library, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/libraries.md#user-content-List%20Libraries
opts := rest.Opts{
Method: "GET",
Path: APIv20,
}
result := make([]api.Library, 1)
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to get libraries: %w", err)
}
return result, nil
}
func (f *Fs) createLibrary(ctx context.Context, libraryName, password string) (library *api.CreateLibrary, err error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/libraries.md#user-content-Create%20Library
opts := rest.Opts{
Method: "POST",
Path: APIv20,
}
request := api.CreateLibraryRequest{
Name: f.opt.Enc.FromStandardName(libraryName),
Description: "Created by rclone",
Password: password,
}
result := &api.CreateLibrary{}
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to create library: %w", err)
}
return result, nil
}
func (f *Fs) deleteLibrary(ctx context.Context, libraryID string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/libraries.md#user-content-Create%20Library
opts := rest.Opts{
Method: "DELETE",
Path: APIv20 + libraryID + "/",
}
result := ""
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fs.ErrorPermissionDenied
}
}
return fmt.Errorf("failed to delete library: %w", err)
}
return nil
}
func (f *Fs) decryptLibrary(ctx context.Context, libraryID, password string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/library-encryption.md#user-content-Decrypt%20Library
if libraryID == "" {
return errors.New("cannot list files without a library")
}
// This is another call that cannot accept a JSON input so we have to build it manually
opts := rest.Opts{
Method: "POST",
Path: APIv20 + libraryID + "/",
ContentType: "application/x-www-form-urlencoded",
Body: bytes.NewBuffer([]byte("password=" + f.opt.Enc.FromStandardName(password))),
NoResponse: true,
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.Call(ctx, &opts)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 400 {
return errors.New("incorrect password")
}
if resp.StatusCode == 409 {
fs.Debugf(nil, "library is not encrypted")
return nil
}
}
return fmt.Errorf("failed to decrypt library: %w", err)
}
return nil
}
func (f *Fs) getDirectoryEntriesAPIv21(ctx context.Context, libraryID, dirPath string, recursive bool) ([]api.DirEntry, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/directories.md#user-content-List%20Items%20in%20Directory
// This is using the undocumented version 2.1 of the API (so we can use the recursive option which is not available in the version 2)
if libraryID == "" {
return nil, errors.New("cannot list files without a library")
}
dirPath = path.Join("/", dirPath)
recursiveFlag := "0"
if recursive {
recursiveFlag = "1"
}
opts := rest.Opts{
Method: "GET",
Path: APIv21 + libraryID + "/dir/",
Parameters: url.Values{
"recursive": {recursiveFlag},
"p": {f.opt.Enc.FromStandardPath(dirPath)},
},
}
result := &api.DirEntries{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return nil, fs.ErrorDirNotFound
}
if resp.StatusCode == 440 {
// Encrypted library and password not provided
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to get directory contents: %w", err)
}
// Clean up encoded names
for index, fileInfo := range result.Entries {
fileInfo.Name = f.opt.Enc.ToStandardName(fileInfo.Name)
fileInfo.Path = f.opt.Enc.ToStandardPath(fileInfo.Path)
result.Entries[index] = fileInfo
}
return result.Entries, nil
}
func (f *Fs) getDirectoryDetails(ctx context.Context, libraryID, dirPath string) (*api.DirectoryDetail, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/directories.md#user-content-Get%20Directory%20Detail
if libraryID == "" {
return nil, errors.New("cannot read directory without a library")
}
dirPath = path.Join("/", dirPath)
opts := rest.Opts{
Method: "GET",
Path: APIv21 + libraryID + "/dir/detail/",
Parameters: url.Values{"path": {f.opt.Enc.FromStandardPath(dirPath)}},
}
result := &api.DirectoryDetail{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return nil, fs.ErrorDirNotFound
}
}
return nil, fmt.Errorf("failed to get directory details: %w", err)
}
result.Name = f.opt.Enc.ToStandardName(result.Name)
result.Path = f.opt.Enc.ToStandardPath(result.Path)
return result, nil
}
// createDir creates a new directory. The API will add a number to the directory name if it already exist
func (f *Fs) createDir(ctx context.Context, libraryID, dirPath string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/directories.md#user-content-Create%20New%20Directory
if libraryID == "" {
return errors.New("cannot create directory without a library")
}
dirPath = path.Join("/", dirPath)
// This call *cannot* handle json parameters in the body, so we have to build the request body manually
opts := rest.Opts{
Method: "POST",
Path: APIv20 + libraryID + "/dir/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(dirPath)}},
NoRedirect: true,
ContentType: "application/x-www-form-urlencoded",
Body: bytes.NewBuffer([]byte("operation=mkdir")),
NoResponse: true,
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.Call(ctx, &opts)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fs.ErrorPermissionDenied
}
}
return fmt.Errorf("failed to create directory: %w", err)
}
return nil
}
func (f *Fs) renameDir(ctx context.Context, libraryID, dirPath, newName string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/directories.md#user-content-Rename%20Directory
if libraryID == "" {
return errors.New("cannot rename directory without a library")
}
dirPath = path.Join("/", dirPath)
// This call *cannot* handle json parameters in the body, so we have to build the request body manually
postParameters := url.Values{
"operation": {"rename"},
"newname": {f.opt.Enc.FromStandardPath(newName)},
}
opts := rest.Opts{
Method: "POST",
Path: APIv20 + libraryID + "/dir/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(dirPath)}},
ContentType: "application/x-www-form-urlencoded",
Body: bytes.NewBuffer([]byte(postParameters.Encode())),
NoResponse: true,
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.Call(ctx, &opts)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fs.ErrorPermissionDenied
}
}
return fmt.Errorf("failed to rename directory: %w", err)
}
return nil
}
func (f *Fs) moveDir(ctx context.Context, srcLibraryID, srcDir, srcName, dstLibraryID, dstPath string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/files-directories-batch-op.md#user-content-Batch%20Move%20Items%20Synchronously
if srcLibraryID == "" || dstLibraryID == "" || srcName == "" {
return errors.New("libraryID and/or file path argument(s) missing")
}
srcDir = path.Join("/", srcDir)
dstPath = path.Join("/", dstPath)
opts := rest.Opts{
Method: "POST",
Path: APIv21 + "sync-batch-move-item/",
NoResponse: true,
}
request := &api.BatchSourceDestRequest{
SrcLibraryID: srcLibraryID,
SrcParentDir: f.opt.Enc.FromStandardPath(srcDir),
SrcItems: []string{f.opt.Enc.FromStandardPath(srcName)},
DstLibraryID: dstLibraryID,
DstParentDir: f.opt.Enc.FromStandardPath(dstPath),
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, nil)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return fs.ErrorObjectNotFound
}
}
return fmt.Errorf("failed to move directory '%s' from '%s' to '%s': %w", srcName, srcDir, dstPath, err)
}
return nil
}
func (f *Fs) deleteDir(ctx context.Context, libraryID, filePath string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/directories.md#user-content-Delete%20Directory
if libraryID == "" {
return errors.New("cannot delete directory without a library")
}
filePath = path.Join("/", filePath)
opts := rest.Opts{
Method: "DELETE",
Path: APIv20 + libraryID + "/dir/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(filePath)}},
NoResponse: true,
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, nil)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fs.ErrorPermissionDenied
}
}
return fmt.Errorf("failed to delete directory: %w", err)
}
return nil
}
func (f *Fs) getFileDetails(ctx context.Context, libraryID, filePath string) (*api.FileDetail, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file.md#user-content-Get%20File%20Detail
if libraryID == "" {
return nil, errors.New("cannot open file without a library")
}
filePath = path.Join("/", filePath)
opts := rest.Opts{
Method: "GET",
Path: APIv20 + libraryID + "/file/detail/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(filePath)}},
}
result := &api.FileDetail{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 404 {
return nil, fs.ErrorObjectNotFound
}
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to get file details: %w", err)
}
result.Name = f.opt.Enc.ToStandardName(result.Name)
result.Parent = f.opt.Enc.ToStandardPath(result.Parent)
return result, nil
}
func (f *Fs) deleteFile(ctx context.Context, libraryID, filePath string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file.md#user-content-Delete%20File
if libraryID == "" {
return errors.New("cannot delete file without a library")
}
filePath = path.Join("/", filePath)
opts := rest.Opts{
Method: "DELETE",
Path: APIv20 + libraryID + "/file/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(filePath)}},
NoResponse: true,
}
err := f.pacer.Call(func() (bool, error) {
resp, err := f.srv.CallJSON(ctx, &opts, nil, nil)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
return fmt.Errorf("failed to delete file: %w", err)
}
return nil
}
func (f *Fs) getDownloadLink(ctx context.Context, libraryID, filePath string) (string, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file.md#user-content-Download%20File
if libraryID == "" {
return "", errors.New("cannot download file without a library")
}
filePath = path.Join("/", filePath)
opts := rest.Opts{
Method: "GET",
Path: APIv20 + libraryID + "/file/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(filePath)}},
}
result := ""
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 404 {
return "", fs.ErrorObjectNotFound
}
}
return "", fmt.Errorf("failed to get download link: %w", err)
}
return result, nil
}
func (f *Fs) download(ctx context.Context, url string, size int64, options ...fs.OpenOption) (io.ReadCloser, error) {
// Check if we need to download partial content
var start, end int64 = 0, size
partialContent := false
for _, option := range options {
switch x := option.(type) {
case *fs.SeekOption:
start = x.Offset
partialContent = true
case *fs.RangeOption:
if x.Start >= 0 {
start = x.Start
if x.End > 0 && x.End < size {
end = x.End + 1
}
} else {
// {-1, 20} should load the last 20 characters [len-20:len]
start = size - x.End
}
partialContent = true
default:
if option.Mandatory() {
fs.Logf(nil, "Unsupported mandatory option: %v", option)
}
}
}
// Build the http request
opts := rest.Opts{
Method: "GET",
RootURL: url,
Options: options,
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.Call(ctx, &opts)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 404 {
return nil, fmt.Errorf("file not found '%s'", url)
}
}
return nil, err
}
// Non-encrypted libraries are accepting the HTTP Range header,
// BUT encrypted libraries are simply ignoring it
if partialContent && resp.StatusCode == 200 {
// Partial content was requested through a Range header, but a full content was sent instead
rangeDownloadNotice.Do(func() {
fs.Logf(nil, "%s ignored our request of partial content. This is probably because encrypted libraries are not accepting range requests. Loading this file might be slow!", f.String())
})
if start > 0 {
// We need to read and discard the beginning of the data...
_, err = io.CopyN(io.Discard, resp.Body, start)
if err != nil {
return nil, err
}
}
// ... and return a limited reader for the remaining of the data
return readers.NewLimitedReadCloser(resp.Body, end-start), nil
}
return resp.Body, nil
}
func (f *Fs) getUploadLink(ctx context.Context, libraryID string) (string, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file-upload.md
if libraryID == "" {
return "", errors.New("cannot upload file without a library")
}
opts := rest.Opts{
Method: "GET",
Path: APIv20 + libraryID + "/upload-link/",
}
result := ""
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return "", fs.ErrorPermissionDenied
}
}
return "", fmt.Errorf("failed to get upload link: %w", err)
}
return result, nil
}
func (f *Fs) upload(ctx context.Context, in io.Reader, uploadLink, filePath string) (*api.FileDetail, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file-upload.md
fileDir, filename := path.Split(filePath)
parameters := url.Values{
"parent_dir": {"/"},
"relative_path": {f.opt.Enc.FromStandardPath(fileDir)},
"need_idx_progress": {"true"},
"replace": {"1"},
}
formReader, contentType, _, err := rest.MultipartUpload(ctx, in, parameters, "file", f.opt.Enc.FromStandardName(filename))
if err != nil {
return nil, fmt.Errorf("failed to make multipart upload: %w", err)
}
opts := rest.Opts{
Method: "POST",
RootURL: uploadLink,
Body: formReader,
ContentType: contentType,
Parameters: url.Values{"ret-json": {"1"}}, // It needs to be on the url, not in the body parameters
}
result := make([]api.FileDetail, 1)
var resp *http.Response
// If an error occurs during the call, do not attempt to retry: The upload link is single use only
err = f.pacer.CallNoRetry(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetryUpload(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 500 {
// This is a temporary error - we will get a new upload link before retrying
return nil, ErrorInternalDuringUpload
}
}
return nil, fmt.Errorf("failed to upload file: %w", err)
}
if len(result) > 0 {
result[0].Parent = f.opt.Enc.ToStandardPath(result[0].Parent)
result[0].Name = f.opt.Enc.ToStandardName(result[0].Name)
return &result[0], nil
}
return nil, nil
}
func (f *Fs) listShareLinks(ctx context.Context, libraryID, remote string) ([]api.SharedLink, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/share-links.md#user-content-List%20Share%20Link%20of%20a%20Folder%20(File)
if libraryID == "" {
return nil, errors.New("cannot get share links without a library")
}
remote = path.Join("/", remote)
opts := rest.Opts{
Method: "GET",
Path: "api/v2.1/share-links/",
Parameters: url.Values{"repo_id": {libraryID}, "path": {f.opt.Enc.FromStandardPath(remote)}},
}
result := make([]api.SharedLink, 1)
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return nil, fs.ErrorObjectNotFound
}
}
return nil, fmt.Errorf("failed to list shared links: %w", err)
}
return result, nil
}
// createShareLink will only work with non-encrypted libraries
func (f *Fs) createShareLink(ctx context.Context, libraryID, remote string) (*api.SharedLink, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/share-links.md#user-content-Create%20Share%20Link
if libraryID == "" {
return nil, errors.New("cannot create a shared link without a library")
}
remote = path.Join("/", remote)
opts := rest.Opts{
Method: "POST",
Path: "api/v2.1/share-links/",
}
request := &api.ShareLinkRequest{
LibraryID: libraryID,
Path: f.opt.Enc.FromStandardPath(remote),
}
result := &api.SharedLink{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return nil, fs.ErrorObjectNotFound
}
}
return nil, fmt.Errorf("failed to create a shared link: %w", err)
}
return result, nil
}
func (f *Fs) copyFile(ctx context.Context, srcLibraryID, srcPath, dstLibraryID, dstPath string) (*api.FileInfo, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file.md#user-content-Copy%20File
// It's using the api/v2.1 which is not in the documentation (as of Apr 2020) but works better than api2
if srcLibraryID == "" || dstLibraryID == "" {
return nil, errors.New("libraryID and/or file path argument(s) missing")
}
srcPath = path.Join("/", srcPath)
dstPath = path.Join("/", dstPath)
opts := rest.Opts{
Method: "POST",
Path: APIv21 + srcLibraryID + "/file/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(srcPath)}},
}
request := &api.FileOperationRequest{
Operation: api.CopyFileOperation,
DestinationLibraryID: dstLibraryID,
DestinationPath: f.opt.Enc.FromStandardPath(dstPath),
}
result := &api.FileInfo{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
fs.Debugf(nil, "Copy: %s", err)
return nil, fs.ErrorObjectNotFound
}
}
return nil, fmt.Errorf("failed to copy file %s:'%s' to %s:'%s': %w", srcLibraryID, srcPath, dstLibraryID, dstPath, err)
}
return f.decodeFileInfo(result), nil
}
func (f *Fs) moveFile(ctx context.Context, srcLibraryID, srcPath, dstLibraryID, dstPath string) (*api.FileInfo, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file.md#user-content-Move%20File
// It's using the api/v2.1 which is not in the documentation (as of Apr 2020) but works better than api2
if srcLibraryID == "" || dstLibraryID == "" {
return nil, errors.New("libraryID and/or file path argument(s) missing")
}
srcPath = path.Join("/", srcPath)
dstPath = path.Join("/", dstPath)
opts := rest.Opts{
Method: "POST",
Path: APIv21 + srcLibraryID + "/file/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(srcPath)}},
}
request := &api.FileOperationRequest{
Operation: api.MoveFileOperation,
DestinationLibraryID: dstLibraryID,
DestinationPath: f.opt.Enc.FromStandardPath(dstPath),
}
result := &api.FileInfo{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
fs.Debugf(nil, "Move: %s", err)
return nil, fs.ErrorObjectNotFound
}
}
return nil, fmt.Errorf("failed to move file %s:'%s' to %s:'%s': %w", srcLibraryID, srcPath, dstLibraryID, dstPath, err)
}
return f.decodeFileInfo(result), nil
}
func (f *Fs) renameFile(ctx context.Context, libraryID, filePath, newname string) (*api.FileInfo, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file.md#user-content-Rename%20File
// It's using the api/v2.1 which is not in the documentation (as of Apr 2020) but works better than api2
if libraryID == "" || newname == "" {
return nil, errors.New("libraryID and/or file path argument(s) missing")
}
filePath = path.Join("/", filePath)
opts := rest.Opts{
Method: "POST",
Path: APIv21 + libraryID + "/file/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(filePath)}},
}
request := &api.FileOperationRequest{
Operation: api.RenameFileOperation,
NewName: f.opt.Enc.FromStandardName(newname),
}
result := &api.FileInfo{}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
fs.Debugf(nil, "Rename: %s", err)
return nil, fs.ErrorObjectNotFound
}
}
return nil, fmt.Errorf("failed to rename file '%s' to '%s': %w", filePath, newname, err)
}
return f.decodeFileInfo(result), nil
}
func (f *Fs) decodeFileInfo(input *api.FileInfo) *api.FileInfo {
input.Name = f.opt.Enc.ToStandardName(input.Name)
input.Path = f.opt.Enc.ToStandardPath(input.Path)
return input
}
func (f *Fs) emptyLibraryTrash(ctx context.Context, libraryID string) error {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/libraries.md#user-content-Clean%20Library%20Trash
if libraryID == "" {
return errors.New("cannot clean up trash without a library")
}
opts := rest.Opts{
Method: "DELETE",
Path: APIv21 + libraryID + "/trash/",
NoResponse: true,
}
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, nil)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return fs.ErrorObjectNotFound
}
}
return fmt.Errorf("failed empty the library trash: %w", err)
}
return nil
}
// === API v2 from the official documentation, but that have been replaced by the much better v2.1 (undocumented as of Apr 2020)
// === getDirectoryEntriesAPIv2 is needed to keep compatibility with seafile v6,
// === the others can probably be removed after the API v2.1 is documented
func (f *Fs) getDirectoryEntriesAPIv2(ctx context.Context, libraryID, dirPath string) ([]api.DirEntry, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/directories.md#user-content-List%20Items%20in%20Directory
if libraryID == "" {
return nil, errors.New("cannot list files without a library")
}
dirPath = path.Join("/", dirPath)
opts := rest.Opts{
Method: "GET",
Path: APIv20 + libraryID + "/dir/",
Parameters: url.Values{"p": {f.opt.Enc.FromStandardPath(dirPath)}},
}
result := make([]api.DirEntry, 1)
var resp *http.Response
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
if resp != nil {
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 404 {
return nil, fs.ErrorDirNotFound
}
if resp.StatusCode == 440 {
// Encrypted library and password not provided
return nil, fs.ErrorPermissionDenied
}
}
return nil, fmt.Errorf("failed to get directory contents: %w", err)
}
// Clean up encoded names
for index, fileInfo := range result {
fileInfo.Name = f.opt.Enc.ToStandardName(fileInfo.Name)
fileInfo.Path = f.opt.Enc.ToStandardPath(fileInfo.Path)
result[index] = fileInfo