forked from rclone/rclone
/
seafile.go
1335 lines (1202 loc) · 38.4 KB
/
seafile.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 (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"sync"
"time"
"github.com/coreos/go-semver/semver"
"github.com/rclone/rclone/backend/seafile/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/cache"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/rest"
)
const (
librariesCacheKey = "all"
retryAfterHeader = "Retry-After"
configURL = "url"
configUser = "user"
configPassword = "pass"
config2FA = "2fa"
configLibrary = "library"
configLibraryKey = "library_key"
configCreateLibrary = "create_library"
configAuthToken = "auth_token"
)
// This is global to all instances of fs
// (copying from a seafile remote to another remote would create 2 fs)
var (
rangeDownloadNotice sync.Once // Display the notice only once
createLibraryMutex sync.Mutex // Mutex to protect library creation
)
// Register with Fs
func init() {
fs.Register(&fs.RegInfo{
Name: "seafile",
Description: "seafile",
NewFs: NewFs,
Config: Config,
Options: []fs.Option{{
Name: configURL,
Help: "URL of seafile host to connect to.",
Required: true,
Examples: []fs.OptionExample{{
Value: "https://cloud.seafile.com/",
Help: "Connect to cloud.seafile.com.",
}},
}, {
Name: configUser,
Help: "User name (usually email address).",
Required: true,
}, {
// Password is not required, it will be left blank for 2FA
Name: configPassword,
Help: "Password.",
IsPassword: true,
}, {
Name: config2FA,
Help: "Two-factor authentication ('true' if the account has 2FA enabled).",
Default: false,
}, {
Name: configLibrary,
Help: "Name of the library.\n\nLeave blank to access all non-encrypted libraries.",
}, {
Name: configLibraryKey,
Help: "Library password (for encrypted libraries only).\n\nLeave blank if you pass it through the command line.",
IsPassword: true,
}, {
Name: configCreateLibrary,
Help: "Should rclone create a library if it doesn't exist.",
Advanced: true,
Default: false,
}, {
// Keep the authentication token after entering the 2FA code
Name: configAuthToken,
Help: "Authentication token.",
Hide: fs.OptionHideBoth,
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
Advanced: true,
Default: (encoder.EncodeZero |
encoder.EncodeCtl |
encoder.EncodeSlash |
encoder.EncodeBackSlash |
encoder.EncodeDoubleQuote |
encoder.EncodeInvalidUtf8),
}},
})
}
// Options defines the configuration for this backend
type Options struct {
URL string `config:"url"`
User string `config:"user"`
Password string `config:"pass"`
Is2FA bool `config:"2fa"`
AuthToken string `config:"auth_token"`
LibraryName string `config:"library"`
LibraryKey string `config:"library_key"`
CreateLibrary bool `config:"create_library"`
Enc encoder.MultiEncoder `config:"encoding"`
}
// Fs represents a remote seafile
type Fs struct {
name string // name of this remote
root string // the path we are working on
libraryName string // current library
encrypted bool // Is this an encrypted library
rootDirectory string // directory part of root (if any)
opt Options // parsed options
libraries *cache.Cache // Keep a cache of libraries
librariesMutex sync.Mutex // Mutex to protect getLibraryID
features *fs.Features // optional features
endpoint *url.URL // URL of the host
endpointURL string // endpoint as a string
srv *rest.Client // the connection to the one drive server
pacer *fs.Pacer // pacer for API calls
authMu sync.Mutex // Mutex to protect library decryption
createDirMutex sync.Mutex // Protect creation of directories
useOldDirectoryAPI bool // Use the old API v2 if seafile < 7
moveDirNotAvailable bool // Version < 7.0 don't have an API to move a directory
}
// ------------------------------------------------------------
// NewFs constructs an Fs from the path, container:path
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
// Parse config into Options struct
opt := new(Options)
err := configstruct.Set(m, opt)
if err != nil {
return nil, err
}
root = strings.Trim(root, "/")
isLibraryRooted := opt.LibraryName != ""
var libraryName, rootDirectory string
if isLibraryRooted {
libraryName = opt.LibraryName
rootDirectory = root
} else {
libraryName, rootDirectory = bucket.Split(root)
}
if !strings.HasSuffix(opt.URL, "/") {
opt.URL += "/"
}
if opt.Password != "" {
var err error
opt.Password, err = obscure.Reveal(opt.Password)
if err != nil {
return nil, fmt.Errorf("couldn't decrypt user password: %w", err)
}
}
if opt.LibraryKey != "" {
var err error
opt.LibraryKey, err = obscure.Reveal(opt.LibraryKey)
if err != nil {
return nil, fmt.Errorf("couldn't decrypt library password: %w", err)
}
}
// Parse the endpoint
u, err := url.Parse(opt.URL)
if err != nil {
return nil, err
}
f := &Fs{
name: name,
root: root,
libraryName: libraryName,
rootDirectory: rootDirectory,
libraries: cache.New(),
opt: *opt,
endpoint: u,
endpointURL: u.String(),
srv: rest.NewClient(fshttp.NewClient(ctx)).SetRoot(u.String()),
pacer: getPacer(ctx, opt.URL),
}
f.features = (&fs.Features{
CanHaveEmptyDirectories: true,
BucketBased: opt.LibraryName == "",
}).Fill(ctx, f)
serverInfo, err := f.getServerInfo(ctx)
if err != nil {
return nil, err
}
fs.Debugf(nil, "Seafile server version %s", serverInfo.Version)
// We don't support lower than seafile v6.0 (version 6.0 is already more than 3 years old)
serverVersion := semver.New(serverInfo.Version)
if serverVersion.Major < 6 {
return nil, errors.New("unsupported Seafile server (version < 6.0)")
}
if serverVersion.Major < 7 {
// Seafile 6 does not support recursive listing
f.useOldDirectoryAPI = true
f.features.ListR = nil
// It also does no support moving directories
f.moveDirNotAvailable = true
}
// Take the authentication token from the configuration first
token := f.opt.AuthToken
if token == "" {
// If not available, send the user/password instead
token, err = f.authorizeAccount(ctx)
if err != nil {
return nil, err
}
}
f.setAuthorizationToken(token)
if f.libraryName != "" {
// Check if the library exists
exists, err := f.libraryExists(ctx, f.libraryName)
if err != nil {
return f, err
}
if !exists {
if f.opt.CreateLibrary {
err := f.mkLibrary(ctx, f.libraryName, "")
if err != nil {
return f, err
}
} else {
return f, fmt.Errorf("library '%s' was not found, and the option to create it is not activated (advanced option)", f.libraryName)
}
}
libraryID, err := f.getLibraryID(ctx, f.libraryName)
if err != nil {
return f, err
}
f.encrypted, err = f.isEncrypted(ctx, libraryID)
if err != nil {
return f, err
}
if f.encrypted {
// If we're inside an encrypted library, let's decrypt it now
err = f.authorizeLibrary(ctx, libraryID)
if err != nil {
return f, err
}
// And remove the public link feature
f.features.PublicLink = nil
}
} else {
// Deactivate the cleaner feature since there's no library selected
f.features.CleanUp = nil
}
if f.rootDirectory != "" {
// Check to see if the root is an existing file
remote := path.Base(rootDirectory)
f.rootDirectory = path.Dir(rootDirectory)
if f.rootDirectory == "." {
f.rootDirectory = ""
}
_, err := f.NewObject(ctx, remote)
if err != nil {
if errors.Is(err, fs.ErrorObjectNotFound) || errors.Is(err, fs.ErrorNotAFile) {
// File doesn't exist so return the original f
f.rootDirectory = rootDirectory
return f, nil
}
return f, err
}
// return an error with an fs which points to the parent
return f, fs.ErrorIsFile
}
return f, nil
}
// Config callback for 2FA
func Config(ctx context.Context, name string, m configmap.Mapper, config fs.ConfigIn) (*fs.ConfigOut, error) {
serverURL, ok := m.Get(configURL)
if !ok || serverURL == "" {
// If there's no server URL, it means we're trying an operation at the backend level, like a "rclone authorize seafile"
return nil, errors.New("operation not supported on this remote. If you need a 2FA code on your account, use the command: rclone config reconnect <remote name>: ")
}
u, err := url.Parse(serverURL)
if err != nil {
return nil, fmt.Errorf("invalid server URL %s", serverURL)
}
is2faEnabled, _ := m.Get(config2FA)
if is2faEnabled != "true" {
// no need to do anything here
return nil, nil
}
username, _ := m.Get(configUser)
if username == "" {
return nil, errors.New("a username is required")
}
password, _ := m.Get(configPassword)
if password != "" {
password, _ = obscure.Reveal(password)
}
switch config.State {
case "":
// Empty state means it's the first call to the Config function
if password == "" {
return fs.ConfigPassword("password", "config_password", "Two-factor authentication: please enter your password (it won't be saved in the configuration)")
}
// password was successfully loaded from the config
return fs.ConfigGoto("2fa")
case "password":
// password should be coming from the previous state (entered by the user)
password = config.Result
if password == "" {
return fs.ConfigError("", "Password can't be blank")
}
// save it into the configuration file and keep going
m.Set(configPassword, obscure.MustObscure(password))
return fs.ConfigGoto("2fa")
case "2fa":
return fs.ConfigInput("2fa_do", "config_2fa", "Two-factor authentication: please enter your 2FA code")
case "2fa_do":
code := config.Result
if code == "" {
return fs.ConfigError("2fa", "2FA codes can't be blank")
}
// Create rest client for getAuthorizationToken
url := u.String()
if !strings.HasPrefix(url, "/") {
url += "/"
}
srv := rest.NewClient(fshttp.NewClient(ctx)).SetRoot(url)
// We loop asking for a 2FA code
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
token, err := getAuthorizationToken(ctx, srv, username, password, code)
if err != nil {
return fs.ConfigConfirm("2fa_error", true, "config_retry", fmt.Sprintf("Authentication failed: %v\n\nTry Again?", err))
}
if token == "" {
return fs.ConfigConfirm("2fa_error", true, "config_retry", "Authentication failed - no token returned.\n\nTry Again?")
}
// Let's save the token into the configuration
m.Set(configAuthToken, token)
// And delete any previous entry for password
m.Set(configPassword, "")
// And we're done here
return nil, nil
case "2fa_error":
if config.Result == "true" {
return fs.ConfigGoto("2fa")
}
return nil, errors.New("2fa authentication failed")
}
return nil, fmt.Errorf("unknown state %q", config.State)
}
// sets the AuthorizationToken up
func (f *Fs) setAuthorizationToken(token string) {
f.srv.SetHeader("Authorization", "Token "+token)
}
// authorizeAccount gets the auth token.
func (f *Fs) authorizeAccount(ctx context.Context) (string, error) {
f.authMu.Lock()
defer f.authMu.Unlock()
token, err := f.getAuthorizationToken(ctx)
if err != nil {
return "", err
}
return token, nil
}
// retryErrorCodes is a slice of error codes that we will retry
var retryErrorCodes = []int{
408, // Request Timeout
429, // Rate exceeded.
500, // Get occasional 500 Internal Server Error
503, // Service Unavailable
504, // Gateway Time-out
520, // Operation failed (We get them sometimes when running tests in parallel)
}
// shouldRetry returns a boolean as to whether this resp and err
// deserve to be retried. It returns the err as a convenience
func (f *Fs) shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
// For 429 errors look at the Retry-After: header and
// set the retry appropriately, starting with a minimum of 1
// second if it isn't set.
if resp != nil && (resp.StatusCode == 429) {
var retryAfter = 1
retryAfterString := resp.Header.Get(retryAfterHeader)
if retryAfterString != "" {
var err error
retryAfter, err = strconv.Atoi(retryAfterString)
if err != nil {
fs.Errorf(f, "Malformed %s header %q: %v", retryAfterHeader, retryAfterString, err)
}
}
return true, pacer.RetryAfterError(err, time.Duration(retryAfter)*time.Second)
}
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
}
func (f *Fs) shouldRetryUpload(ctx context.Context, resp *http.Response, err error) (bool, error) {
if err != nil || (resp != nil && resp.StatusCode > 400) {
return true, err
}
return false, nil
}
// Name of the remote (as passed into NewFs)
func (f *Fs) Name() string {
return f.name
}
// Root of the remote (as passed into NewFs)
func (f *Fs) Root() string {
return f.root
}
// String converts this Fs to a string
func (f *Fs) String() string {
if f.libraryName == "" {
return "seafile root"
}
library := "library"
if f.encrypted {
library = "encrypted " + library
}
if f.rootDirectory == "" {
return fmt.Sprintf("seafile %s '%s'", library, f.libraryName)
}
return fmt.Sprintf("seafile %s '%s' path '%s'", library, f.libraryName, f.rootDirectory)
}
// Precision of the ModTimes in this Fs
func (f *Fs) Precision() time.Duration {
// The API doesn't support setting the modified time
return fs.ModTimeNotSupported
}
// Hashes returns the supported hash sets.
func (f *Fs) Hashes() hash.Set {
return hash.Set(hash.None)
}
// Features returns the optional features of this Fs
func (f *Fs) Features() *fs.Features {
return f.features
}
// List the objects and directories in dir into entries. The
// entries can be returned in any order but should be for a
// complete directory.
//
// dir should be "" to list the root, and should not have
// trailing slashes.
//
// This should return fs.ErrorDirNotFound if the directory isn't
// found.
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
if dir == "" && f.libraryName == "" {
return f.listLibraries(ctx)
}
return f.listDir(ctx, dir, false)
}
// NewObject finds the Object at remote. If it can't be found
// it returns the error fs.ErrorObjectNotFound.
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
libraryName, filePath := f.splitPath(remote)
libraryID, err := f.getLibraryID(ctx, libraryName)
if err != nil {
return nil, err
}
err = f.authorizeLibrary(ctx, libraryID)
if err != nil {
return nil, err
}
fileDetails, err := f.getFileDetails(ctx, libraryID, filePath)
if err != nil {
return nil, err
}
modTime, err := time.Parse(time.RFC3339, fileDetails.Modified)
if err != nil {
fs.LogPrintf(fs.LogLevelWarning, fileDetails.Modified, "Cannot parse datetime")
}
o := &Object{
fs: f,
libraryID: libraryID,
id: fileDetails.ID,
remote: remote,
pathInLibrary: filePath,
modTime: modTime,
size: fileDetails.Size,
}
return o, nil
}
// Put in to the remote path with the modTime given of the given size
//
// When called from outside an Fs by rclone, src.Size() will always be >= 0.
// But for unknown-sized objects (indicated by src.Size() == -1), Put should either
// return an error or upload it properly (rather than e.g. calling panic).
//
// May create the object even if it returns an error - if so
// will return the object and the error, otherwise will return
// nil and the error
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
object := f.newObject(ctx, src.Remote(), src.Size(), src.ModTime(ctx))
// Check if we need to create a new library at that point
if object.libraryID == "" {
library, _ := f.splitPath(object.remote)
err := f.Mkdir(ctx, library)
if err != nil {
return object, err
}
libraryID, err := f.getLibraryID(ctx, library)
if err != nil {
return object, err
}
object.libraryID = libraryID
}
err := object.Update(ctx, in, src, options...)
if err != nil {
return object, err
}
return object, nil
}
// PutStream uploads to the remote path with the modTime given but of indeterminate size
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
return f.Put(ctx, in, src, options...)
}
// Mkdir makes the directory or library
//
// Shouldn't return an error if it already exists
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
libraryName, folder := f.splitPath(dir)
if strings.HasPrefix(dir, libraryName) {
err := f.mkLibrary(ctx, libraryName, "")
if err != nil {
return err
}
if folder == "" {
// No directory to create after the library
return nil
}
}
err := f.mkDir(ctx, dir)
if err != nil {
return err
}
return nil
}
// purgeCheck removes the root directory, if check is set then it
// refuses to do so if it has anything in
func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
libraryName, dirPath := f.splitPath(dir)
libraryID, err := f.getLibraryID(ctx, libraryName)
if err != nil {
return err
}
if check {
directoryEntries, err := f.getDirectoryEntries(ctx, libraryID, dirPath, false)
if err != nil {
return err
}
if len(directoryEntries) > 0 {
return fs.ErrorDirectoryNotEmpty
}
}
if dirPath == "" || dirPath == "/" {
return f.deleteLibrary(ctx, libraryID)
}
return f.deleteDir(ctx, libraryID, dirPath)
}
// Rmdir removes the directory or library if empty
//
// Return an error if it doesn't exist or isn't empty
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
return f.purgeCheck(ctx, dir, true)
}
// ==================== Optional Interface fs.ListRer ====================
// ListR lists the objects and directories of the Fs starting
// from dir recursively into out.
//
// dir should be "" to start from the root, and should not
// have trailing slashes.
//
// This should return ErrDirNotFound if the directory isn't
// found.
//
// It should call callback for each tranche of entries read.
// These need not be returned in any particular order. If
// callback returns an error then the listing will stop
// immediately.
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) error {
var err error
if dir == "" && f.libraryName == "" {
libraries, err := f.listLibraries(ctx)
if err != nil {
return err
}
// Send the library list as folders
err = callback(libraries)
if err != nil {
return err
}
// Then list each library
for _, library := range libraries {
err = f.listDirCallback(ctx, library.Remote(), callback)
if err != nil {
return err
}
}
return nil
}
err = f.listDirCallback(ctx, dir, callback)
if err != nil {
return err
}
return nil
}
// ==================== Optional Interface fs.Copier ====================
// Copy src to this remote using server-side copy operations.
//
// This is stored with the remote path given
//
// It returns the destination Object and a possible error
//
// If it isn't possible then return fs.ErrorCantCopy
func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
srcObj, ok := src.(*Object)
if !ok {
return nil, fs.ErrorCantCopy
}
srcLibraryName, srcPath := srcObj.fs.splitPath(src.Remote())
srcLibraryID, err := srcObj.fs.getLibraryID(ctx, srcLibraryName)
if err != nil {
return nil, err
}
dstLibraryName, dstPath := f.splitPath(remote)
dstLibraryID, err := f.getLibraryID(ctx, dstLibraryName)
if err != nil {
return nil, err
}
// Seafile does not accept a file name as a destination, only a path.
// The destination filename will be the same as the original, or with (1) added in case it was already existing
dstDir, dstFilename := path.Split(dstPath)
// We have to make sure the destination path exists on the server or it's going to bomb out with an obscure error message
err = f.mkMultiDir(ctx, dstLibraryID, dstDir)
if err != nil {
return nil, err
}
op, err := f.copyFile(ctx, srcLibraryID, srcPath, dstLibraryID, dstDir)
if err != nil {
return nil, err
}
if op.Name != dstFilename {
// Destination was existing, so we need to move the file back into place
err = f.adjustDestination(ctx, dstLibraryID, op.Name, dstPath, dstDir, dstFilename)
if err != nil {
return nil, err
}
}
// Create a new object from the result
return f.NewObject(ctx, remote)
}
// ==================== Optional Interface fs.Mover ====================
// Move src to this remote using server-side move operations.
//
// This is stored with the remote path given
//
// It returns the destination Object and a possible error
//
// If it isn't possible then return fs.ErrorCantMove
func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
srcObj, ok := src.(*Object)
if !ok {
return nil, fs.ErrorCantMove
}
srcLibraryName, srcPath := srcObj.fs.splitPath(src.Remote())
srcLibraryID, err := srcObj.fs.getLibraryID(ctx, srcLibraryName)
if err != nil {
return nil, err
}
dstLibraryName, dstPath := f.splitPath(remote)
dstLibraryID, err := f.getLibraryID(ctx, dstLibraryName)
if err != nil {
return nil, err
}
// anchor both source and destination paths from the root so we can compare them
srcPath = path.Join("/", srcPath)
dstPath = path.Join("/", dstPath)
srcDir := path.Dir(srcPath)
dstDir, dstFilename := path.Split(dstPath)
if srcLibraryID == dstLibraryID && srcDir == dstDir {
// It's only a simple case of renaming the file
_, err := f.renameFile(ctx, srcLibraryID, srcPath, dstFilename)
if err != nil {
return nil, err
}
return f.NewObject(ctx, remote)
}
// We have to make sure the destination path exists on the server
err = f.mkMultiDir(ctx, dstLibraryID, dstDir)
if err != nil {
return nil, err
}
// Seafile does not accept a file name as a destination, only a path.
// The destination filename will be the same as the original, or with (1) added in case it already exists
op, err := f.moveFile(ctx, srcLibraryID, srcPath, dstLibraryID, dstDir)
if err != nil {
return nil, err
}
if op.Name != dstFilename {
// Destination was existing, so we need to move the file back into place
err = f.adjustDestination(ctx, dstLibraryID, op.Name, dstPath, dstDir, dstFilename)
if err != nil {
return nil, err
}
}
// Create a new object from the result
return f.NewObject(ctx, remote)
}
// adjustDestination rename the file
func (f *Fs) adjustDestination(ctx context.Context, libraryID, srcFilename, dstPath, dstDir, dstFilename string) error {
// Seafile seems to be acting strangely if the renamed file already exists (some cache issue maybe?)
// It's better to delete the destination if it already exists
fileDetail, err := f.getFileDetails(ctx, libraryID, dstPath)
if err != nil && err != fs.ErrorObjectNotFound {
return err
}
if fileDetail != nil {
err = f.deleteFile(ctx, libraryID, dstPath)
if err != nil {
return err
}
}
_, err = f.renameFile(ctx, libraryID, path.Join(dstDir, srcFilename), dstFilename)
if err != nil {
return err
}
return nil
}
// ==================== Optional Interface fs.DirMover ====================
// DirMove moves src, srcRemote to this remote at dstRemote
// using server-side move operations.
//
// Will only be called if src.Fs().Name() == f.Name()
//
// If it isn't possible then return fs.ErrorCantDirMove
//
// If destination exists then return fs.ErrorDirExists
func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error {
// Cast into a seafile Fs
srcFs, ok := src.(*Fs)
if !ok {
return fs.ErrorCantDirMove
}
srcLibraryName, srcPath := srcFs.splitPath(srcRemote)
srcLibraryID, err := srcFs.getLibraryID(ctx, srcLibraryName)
if err != nil {
return err
}
dstLibraryName, dstPath := f.splitPath(dstRemote)
dstLibraryID, err := f.getLibraryID(ctx, dstLibraryName)
if err != nil {
return err
}
srcDir := path.Dir(srcPath)
dstDir, dstName := path.Split(dstPath)
// anchor both source and destination to the root so we can compare them
srcDir = path.Join("/", srcDir)
dstDir = path.Join("/", dstDir)
// The destination should not exist
entries, err := f.getDirectoryEntries(ctx, dstLibraryID, dstDir, false)
if err != nil && err != fs.ErrorDirNotFound {
return err
}
if err == nil {
for _, entry := range entries {
if entry.Name == dstName {
// Destination exists
return fs.ErrorDirExists
}
}
}
if srcLibraryID == dstLibraryID && srcDir == dstDir {
// It's only renaming
err = srcFs.renameDir(ctx, dstLibraryID, srcPath, dstName)
if err != nil {
return err
}
return nil
}
// Seafile < 7 does not support moving directories
if f.moveDirNotAvailable {
return fs.ErrorCantDirMove
}
// Make sure the destination path exists
err = f.mkMultiDir(ctx, dstLibraryID, dstDir)
if err != nil {
return err
}
// If the destination already exists, seafile will add a " (n)" to the name.
// Sadly this API call will not return the new given name like the move file version does
// So the trick is to rename the directory to something random before moving it
// After the move we rename the random name back to the expected one
// Hopefully there won't be anything with the same name existing at destination ;)
tempName := ".rclone-move-" + random.String(32)
// 1- rename source
err = srcFs.renameDir(ctx, srcLibraryID, srcPath, tempName)
if err != nil {
return fmt.Errorf("cannot rename source directory to a temporary name: %w", err)
}
// 2- move source to destination
err = f.moveDir(ctx, srcLibraryID, srcDir, tempName, dstLibraryID, dstDir)
if err != nil {
// Doh! Let's rename the source back to its original name
_ = srcFs.renameDir(ctx, srcLibraryID, path.Join(srcDir, tempName), path.Base(srcPath))
return err
}
// 3- rename destination back to source name
err = f.renameDir(ctx, dstLibraryID, path.Join(dstDir, tempName), dstName)
if err != nil {
return fmt.Errorf("cannot rename temporary directory to destination name: %w", err)
}
return nil
}
// ==================== Optional Interface fs.Purger ====================
// Purge all files in the directory
//
// Implement this if you have a way of deleting all the files
// quicker than just running Remove() on the result of List()
//
// Return an error if it doesn't exist
func (f *Fs) Purge(ctx context.Context, dir string) error {
return f.purgeCheck(ctx, dir, false)
}
// ==================== Optional Interface fs.CleanUpper ====================
// CleanUp the trash in the Fs
func (f *Fs) CleanUp(ctx context.Context) error {
if f.libraryName == "" {
return errors.New("cannot clean up at the root of the seafile server, please select a library to clean up")
}
libraryID, err := f.getLibraryID(ctx, f.libraryName)
if err != nil {
return err
}
return f.emptyLibraryTrash(ctx, libraryID)
}
// ==================== Optional Interface fs.Abouter ====================
// About gets quota information
func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
accountInfo, err := f.getUserAccountInfo(ctx)
if err != nil {
return nil, err
}
usage = &fs.Usage{
Used: fs.NewUsageValue(accountInfo.Usage), // bytes in use
}
if accountInfo.Total > 0 {
usage.Total = fs.NewUsageValue(accountInfo.Total) // quota of bytes that can be used
usage.Free = fs.NewUsageValue(accountInfo.Total - accountInfo.Usage) // bytes which can be uploaded before reaching the quota
}
return usage, nil
}
// ==================== Optional Interface fs.UserInfoer ====================
// UserInfo returns info about the connected user
func (f *Fs) UserInfo(ctx context.Context) (map[string]string, error) {
accountInfo, err := f.getUserAccountInfo(ctx)
if err != nil {
return nil, err
}
return map[string]string{
"Name": accountInfo.Name,
"Email": accountInfo.Email,
}, nil
}
// ==================== Optional Interface fs.PublicLinker ====================
// PublicLink generates a public link to the remote path (usually readable by anyone)
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) {
libraryName, filePath := f.splitPath(remote)
if libraryName == "" {
// We cannot share the whole seafile server, we need at least a library
return "", errors.New("cannot share the root of the seafile server, please select a library to share")
}
libraryID, err := f.getLibraryID(ctx, libraryName)
if err != nil {
return "", err
}
// List existing links first
shareLinks, err := f.listShareLinks(ctx, libraryID, filePath)
if err != nil {
return "", err
}
if len(shareLinks) > 0 {
for _, shareLink := range shareLinks {
if !shareLink.IsExpired {
return shareLink.Link, nil
}
}
}
// No link was found
shareLink, err := f.createShareLink(ctx, libraryID, filePath)
if err != nil {
return "", err
}
if shareLink.IsExpired {
return "", nil