-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
HybridFile.java
1943 lines (1827 loc) · 66.5 KB
/
HybridFile.java
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
/*
* Copyright (C) 2014-2020 Arpit Khurana <arpitkh96@gmail.com>, Vishal Nehra <vishalmeham2@gmail.com>,
* Emmanuel Messulam<emmanuelbendavid@gmail.com>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem;
import static com.amaze.filemanager.filesystem.FileProperties.ANDROID_DATA_DIRS;
import static com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTPS_URI_PREFIX;
import static com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTP_URI_PREFIX;
import static com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SSH_URI_PREFIX;
import static com.amaze.filemanager.filesystem.ftp.NetCopyConnectionInfo.MULTI_SLASH;
import static com.amaze.filemanager.filesystem.smb.CifsContexts.SMB_URI_PREFIX;
import static com.amaze.filemanager.filesystem.ssh.SFTPClientExtKt.READ_AHEAD_MAX_UNCONFIRMED_READS;
import static com.amaze.filemanager.filesystem.ssh.SshClientUtils.sftpGetSize;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amaze.filemanager.R;
import com.amaze.filemanager.adapters.data.LayoutElementParcelable;
import com.amaze.filemanager.application.AppConfig;
import com.amaze.filemanager.database.CloudHandler;
import com.amaze.filemanager.fileoperations.exceptions.CloudPluginException;
import com.amaze.filemanager.fileoperations.exceptions.ShellNotRunningException;
import com.amaze.filemanager.fileoperations.filesystem.OpenMode;
import com.amaze.filemanager.fileoperations.filesystem.root.NativeOperations;
import com.amaze.filemanager.filesystem.cloud.CloudUtil;
import com.amaze.filemanager.filesystem.files.FileUtils;
import com.amaze.filemanager.filesystem.files.GenericCopyUtil;
import com.amaze.filemanager.filesystem.files.MediaConnectionUtils;
import com.amaze.filemanager.filesystem.ftp.ExtensionsKt;
import com.amaze.filemanager.filesystem.ftp.FTPClientImpl;
import com.amaze.filemanager.filesystem.ftp.FtpClientTemplate;
import com.amaze.filemanager.filesystem.ftp.NetCopyClientUtils;
import com.amaze.filemanager.filesystem.ftp.NetCopyConnectionInfo;
import com.amaze.filemanager.filesystem.root.DeleteFileCommand;
import com.amaze.filemanager.filesystem.root.ListFilesCommand;
import com.amaze.filemanager.filesystem.ssh.SFTPClientExtKt;
import com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate;
import com.amaze.filemanager.filesystem.ssh.SshClientSessionTemplate;
import com.amaze.filemanager.filesystem.ssh.SshClientUtils;
import com.amaze.filemanager.filesystem.ssh.Statvfs;
import com.amaze.filemanager.ui.activities.MainActivity;
import com.amaze.filemanager.ui.dialogs.GeneralDialogCreation;
import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.OnFileFound;
import com.amaze.filemanager.utils.Utils;
import com.amaze.filemanager.utils.smb.SmbUtil;
import com.amaze.trashbin.TrashBin;
import com.amaze.trashbin.TrashBinFile;
import com.cloudrail.si.interfaces.CloudStorage;
import com.cloudrail.si.types.SpaceAllocation;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.arch.core.util.Function;
import androidx.documentfile.provider.DocumentFile;
import androidx.preference.PreferenceManager;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import kotlin.collections.ArraysKt;
import kotlin.io.ByteStreamsKt;
import kotlin.text.Charsets;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.FileMode;
import net.schmizz.sshj.sftp.RemoteFile;
import net.schmizz.sshj.sftp.RemoteResourceInfo;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.sftp.SFTPException;
/** Hybrid file for handeling all types of files */
public class HybridFile {
private static final Logger LOG = LoggerFactory.getLogger(HybridFile.class);
public static final String DOCUMENT_FILE_PREFIX =
"content://com.android.externalstorage.documents";
protected String path;
protected OpenMode mode;
protected String name;
private final DataUtils dataUtils = DataUtils.getInstance();
public HybridFile(OpenMode mode, String path) {
this.path = path;
this.mode = mode;
sanitizePathAsNecessary();
}
public HybridFile(OpenMode mode, String path, String name, boolean isDirectory) {
this(mode, path);
this.name = name;
if (path.startsWith(SMB_URI_PREFIX) || isSmb() || isDocumentFile() || isOtgFile()) {
Uri.Builder pathBuilder = Uri.parse(this.path).buildUpon().appendEncodedPath(name);
if ((path.startsWith(SMB_URI_PREFIX) || isSmb()) && isDirectory) {
pathBuilder.appendEncodedPath("/");
}
this.path = pathBuilder.build().toString();
} else if (path.startsWith(SSH_URI_PREFIX) || isSftp()) {
this.path += "/" + name;
} else if (isRoot() && path.equals("/")) {
// root of filesystem, don't concat another '/'
this.path += name;
} else if (isTrashBin()) {
this.path = path;
} else {
this.path += "/" + name;
}
sanitizePathAsNecessary();
}
public void generateMode(Context context) {
if (path.startsWith(SMB_URI_PREFIX)) {
mode = OpenMode.SMB;
} else if (path.startsWith(SSH_URI_PREFIX)) {
mode = OpenMode.SFTP;
} else if (path.startsWith(OTGUtil.PREFIX_OTG)) {
mode = OpenMode.OTG;
} else if (path.startsWith(FTP_URI_PREFIX) || path.startsWith(FTPS_URI_PREFIX)) {
mode = OpenMode.FTP;
} else if (path.startsWith(DOCUMENT_FILE_PREFIX)) {
mode = OpenMode.DOCUMENT_FILE;
} else if (isCustomPath()) {
mode = OpenMode.CUSTOM;
} else if (path.startsWith(CloudHandler.CLOUD_PREFIX_BOX)) {
mode = OpenMode.BOX;
} else if (path.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE)) {
mode = OpenMode.ONEDRIVE;
} else if (path.startsWith(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE)) {
mode = OpenMode.GDRIVE;
} else if (path.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX)) {
mode = OpenMode.DROPBOX;
} else if (path.equals("7") || isTrashBin()) {
mode = OpenMode.TRASH_BIN;
} else if (context == null) {
mode = OpenMode.FILE;
} else {
boolean rootmode =
PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(PreferencesConstants.PREFERENCE_ROOTMODE, false);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
mode = OpenMode.FILE;
if (rootmode && !getFile().canRead()) {
mode = OpenMode.ROOT;
}
} else {
if (ExternalSdCardOperation.isOnExtSdCard(getFile(), context)) {
mode = OpenMode.FILE;
} else if (rootmode && !getFile().canRead()) {
mode = OpenMode.ROOT;
}
// In some cases, non-numeric path is passed into HybridFile while mode is still
// CUSTOM here. We are forcing OpenMode.FILE in such case too. See #2225
if (OpenMode.UNKNOWN.equals(mode) || OpenMode.CUSTOM.equals(mode)) {
mode = OpenMode.FILE;
}
}
}
}
public void setMode(OpenMode mode) {
this.mode = mode;
}
public OpenMode getMode() {
return mode;
}
public void setPath(String path) {
this.path = path;
}
public boolean isLocal() {
return mode == OpenMode.FILE;
}
public boolean isRoot() {
return mode == OpenMode.ROOT;
}
public boolean isTrashBin() {
return mode == OpenMode.TRASH_BIN;
}
public boolean isSmb() {
return mode == OpenMode.SMB;
}
public boolean isSftp() {
return mode == OpenMode.SFTP;
}
public boolean isOtgFile() {
return mode == OpenMode.OTG;
}
public boolean isFtp() {
return mode == OpenMode.FTP;
}
public boolean isDocumentFile() {
return mode == OpenMode.DOCUMENT_FILE;
}
public boolean isBoxFile() {
return mode == OpenMode.BOX;
}
public boolean isDropBoxFile() {
return mode == OpenMode.DROPBOX;
}
public boolean isOneDriveFile() {
return mode == OpenMode.ONEDRIVE;
}
public boolean isGoogleDriveFile() {
return mode == OpenMode.GDRIVE;
}
public boolean isAndroidDataDir() {
return mode == OpenMode.ANDROID_DATA;
}
public boolean isCloudDriveFile() {
return isBoxFile() || isDropBoxFile() || isOneDriveFile() || isGoogleDriveFile();
}
@Nullable
public File getFile() {
return new File(path);
}
@Nullable
public DocumentFile getDocumentFile(boolean createRecursive) {
return OTGUtil.getDocumentFile(
path,
SafRootHolder.getUriRoot(),
AppConfig.getInstance(),
OpenMode.DOCUMENT_FILE,
createRecursive);
}
HybridFileParcelable generateBaseFileFromParent() {
ArrayList<HybridFileParcelable> arrayList =
RootHelper.getFilesList(getFile().getParent(), true, true);
for (HybridFileParcelable baseFile : arrayList) {
if (baseFile.getPath().equals(path)) return baseFile;
}
return null;
}
public long lastModified() {
switch (mode) {
case SFTP:
final Long returnValue =
SshClientUtils.execute(
new SFtpClientTemplate<Long>(path, true) {
@Override
public Long execute(@NonNull SFTPClient client) throws IOException {
return client.mtime(NetCopyClientUtils.extractRemotePathFrom(path));
}
});
if (returnValue == null) {
LOG.error("Error obtaining last modification time over SFTP");
}
return returnValue == null ? 0L : returnValue;
case SMB:
SmbFile smbFile = getSmbFile();
if (smbFile != null) {
try {
return smbFile.lastModified();
} catch (SmbException e) {
LOG.error("Error getting last modified time for SMB [" + path + "]", e);
return 0;
}
}
break;
case FTP:
FTPFile ftpFile = getFtpFile();
return ftpFile != null ? ftpFile.getTimestamp().getTimeInMillis() : 0L;
case NFS:
break;
case FILE:
case TRASH_BIN:
return getFile().lastModified();
case DOCUMENT_FILE:
return getDocumentFile(false).lastModified();
case ROOT:
HybridFileParcelable baseFile = generateBaseFileFromParent();
if (baseFile != null) return baseFile.getDate();
}
return new File("/").lastModified();
}
/** Helper method to find length */
public long length(Context context) {
long s = 0L;
switch (mode) {
case SFTP:
if (this instanceof HybridFileParcelable) {
return ((HybridFileParcelable) this).getSize();
} else {
return sftpGetSize.invoke(getPath());
}
case SMB:
s =
Single.fromCallable(
() -> {
SmbFile smbFile = getSmbFile();
if (smbFile != null) {
try {
return smbFile.length();
} catch (SmbException e) {
LOG.warn("failed to get length for smb file", e);
return 0L;
}
} else {
return 0L;
}
})
.subscribeOn(Schedulers.io())
.blockingGet();
return s;
case FTP:
FTPFile ftpFile = getFtpFile();
s = ftpFile != null ? ftpFile.getSize() : 0L;
return s;
case NFS:
case FILE:
case TRASH_BIN:
s = getFile().length();
return s;
case ROOT:
HybridFileParcelable baseFile = generateBaseFileFromParent();
if (baseFile != null) return baseFile.getSize();
break;
case DOCUMENT_FILE:
s = getDocumentFile(false).length();
break;
case OTG:
s = OTGUtil.getDocumentFile(path, context, false).length();
break;
case DROPBOX:
case BOX:
case ONEDRIVE:
case GDRIVE:
s =
Single.fromCallable(
() ->
dataUtils
.getAccount(mode)
.getMetadata(CloudUtil.stripPath(mode, path))
.getSize())
.subscribeOn(Schedulers.io())
.blockingGet();
return s;
default:
break;
}
return s;
}
/**
* Path accessor. Avoid direct access to path (for non-local files) since path may have been URL
* encoded.
*
* @return URL decoded path (for non-local files); the actual path for local files
*/
public String getPath() {
if (isLocal() || isTrashBin() || isRoot() || isDocumentFile() || isAndroidDataDir())
return path;
try {
return URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
LOG.warn("failed to decode path {}", path, e);
return path;
}
}
public String getSimpleName() {
String name = null;
switch (mode) {
case SMB:
SmbFile smbFile = getSmbFile();
if (smbFile != null) return smbFile.getName();
break;
default:
StringBuilder builder = new StringBuilder(path);
name = builder.substring(builder.lastIndexOf("/") + 1, builder.length());
}
return name;
}
public String getName(Context context) {
switch (mode) {
case SMB:
SmbFile smbFile = getSmbFile();
if (smbFile != null) {
return smbFile.getName();
}
return null;
case FILE:
case ROOT:
return getFile().getName();
case OTG:
if (!Utils.isNullOrEmpty(name)) {
return name;
}
return OTGUtil.getDocumentFile(path, context, false).getName();
case DOCUMENT_FILE:
if (!Utils.isNullOrEmpty(name)) {
return name;
}
return OTGUtil.getDocumentFile(
path, SafRootHolder.getUriRoot(), context, OpenMode.DOCUMENT_FILE, false)
.getName();
case TRASH_BIN:
return name;
default:
if (path.isEmpty()) {
return "";
}
String _path = null;
try {
_path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
LOG.warn("failed to decode path {}", path, e);
}
if (path.endsWith("/")) {
_path = path.substring(0, path.length() - 1);
}
int lastSeparator = _path.lastIndexOf('/');
return _path.substring(lastSeparator + 1);
}
}
public SmbFile getSmbFile(int timeout) {
try {
SmbFile smbFile = SmbUtil.create(path);
smbFile.setConnectTimeout(timeout);
return smbFile;
} catch (MalformedURLException e) {
LOG.warn("failed to get smb file with timeout", e);
return null;
}
}
public SmbFile getSmbFile() {
try {
return SmbUtil.create(path);
} catch (MalformedURLException e) {
LOG.warn("failed to get smb file", e);
return null;
}
}
@Nullable
public FTPFile getFtpFile() {
return NetCopyClientUtils.INSTANCE.execute(
new FtpClientTemplate<FTPFile>(path, false) {
public FTPFile executeWithFtpClient(@NonNull FTPClient ftpClient) throws IOException {
String path =
NetCopyClientUtils.extractRemotePathFrom(getParent(AppConfig.getInstance()));
ftpClient.changeWorkingDirectory(path);
for (FTPFile ftpFile : ftpClient.listFiles()) {
if (ftpFile.getName().equals(getName(AppConfig.getInstance()))) return ftpFile;
}
return null;
}
});
}
public boolean isCustomPath() {
return path.equals("0")
|| path.equals("1")
|| path.equals("2")
|| path.equals("3")
|| path.equals("4")
|| path.equals("5")
|| path.equals("6");
}
/** Helper method to get parent path */
@Nullable
public String getParent(Context context) {
switch (mode) {
case SMB:
SmbFile smbFile = getSmbFile();
if (smbFile != null) {
return smbFile.getParent();
}
return "";
case FILE:
case ROOT:
return getFile().getParent();
case TRASH_BIN:
return "7";
case SFTP:
case DOCUMENT_FILE:
String thisPath = path;
if (thisPath.contains("%")) {
try {
thisPath = URLDecoder.decode(getPath(), Charsets.UTF_8.name());
} catch (UnsupportedEncodingException ignored) {
}
}
List<String> pathSegments = Uri.parse(thisPath).getPathSegments();
if (thisPath.isEmpty() || pathSegments.isEmpty()) return null;
String currentName = pathSegments.get(pathSegments.size() - 1);
int currentNameStartIndex = thisPath.lastIndexOf(currentName);
if (currentNameStartIndex < 0) {
return null;
}
String parent = thisPath.substring(0, currentNameStartIndex);
if (ArraysKt.any(ANDROID_DATA_DIRS, dir -> parent.endsWith(dir + "/"))) {
return FileProperties.unmapPathForApi30OrAbove(parent);
} else {
return parent;
}
default:
if (getPath().length() <= getName(context).length()) {
return null;
}
int start = 0;
int end = getPath().length() - getName(context).length() - 1;
return getPath().substring(start, end);
}
}
/**
* Whether this object refers to a directory or file, handles all types of files
*
* @deprecated use {@link #isDirectory(Context)} to handle content resolvers
*/
public boolean isDirectory() {
boolean isDirectory;
switch (mode) {
case SFTP:
case FTP:
case SMB:
return isDirectory(AppConfig.getInstance());
case ROOT:
isDirectory = NativeOperations.isDirectory(path);
break;
case DOCUMENT_FILE:
return getDocumentFile(false).isDirectory();
case OTG:
// TODO: support for this method in OTG on-the-fly
// you need to manually call {@link RootHelper#getDocumentFile() method
isDirectory = false;
break;
case FILE:
case TRASH_BIN:
default:
isDirectory = getFile().isDirectory();
break;
}
return isDirectory;
}
public boolean isDirectory(Context context) {
switch (mode) {
case SFTP:
final Boolean returnValue =
SshClientUtils.execute(
new SFtpClientTemplate<Boolean>(path, true) {
@Override
public Boolean execute(@NonNull SFTPClient client) {
try {
return client
.stat(NetCopyClientUtils.extractRemotePathFrom(path))
.getType()
.equals(FileMode.Type.DIRECTORY);
} catch (IOException notFound) {
LOG.error("Fail to execute isDirectory for SFTP path :" + path, notFound);
return false;
}
}
});
if (returnValue == null) {
LOG.error("Error obtaining if path is directory over SFTP");
return false;
}
return returnValue;
case SMB:
try {
return Single.fromCallable(() -> getSmbFile().isDirectory())
.subscribeOn(Schedulers.io())
.blockingGet();
} catch (Exception e) {
LOG.warn("failed to get isDirectory with context for smb file", e);
return false;
}
case FTP:
FTPFile ftpFile = getFtpFile();
return ftpFile != null && ftpFile.isDirectory();
case ROOT:
return NativeOperations.isDirectory(path);
case DOCUMENT_FILE:
DocumentFile documentFile = getDocumentFile(false);
return documentFile != null && documentFile.isDirectory();
case OTG:
DocumentFile otgFile = OTGUtil.getDocumentFile(path, context, false);
return otgFile != null && otgFile.isDirectory();
case DROPBOX:
case BOX:
case GDRIVE:
case ONEDRIVE:
return Single.fromCallable(
() ->
dataUtils
.getAccount(mode)
.getMetadata(CloudUtil.stripPath(mode, path))
.getFolder())
.subscribeOn(Schedulers.io())
.blockingGet();
case TRASH_BIN:
default: // also handles the case `FILE`
File file = getFile();
return file != null && file.isDirectory();
}
}
/**
* @deprecated use {@link #folderSize(Context)}
*/
public long folderSize() {
long size = 0L;
switch (mode) {
case SFTP:
case FTP:
return folderSize(AppConfig.getInstance());
case SMB:
SmbFile smbFile = getSmbFile();
size = smbFile != null ? FileUtils.folderSize(getSmbFile()) : 0;
break;
case FILE:
case TRASH_BIN:
size = FileUtils.folderSize(getFile(), null);
break;
case ROOT:
HybridFileParcelable baseFile = generateBaseFileFromParent();
if (baseFile != null) size = baseFile.getSize();
break;
default:
return 0L;
}
return size;
}
/** Helper method to get length of folder in an otg */
public long folderSize(Context context) {
long size = 0L;
switch (mode) {
case SFTP:
Long retval = -1L;
String result = SshClientUtils.execute(getRemoteShellCommandLineResult("du -bs \"%s\""));
if (!TextUtils.isEmpty(result) && result.indexOf('\t') > 0) {
try {
retval = Long.valueOf(result.substring(0, result.lastIndexOf('\t')));
} catch (NumberFormatException ifParseFailed) {
LOG.warn("Unable to parse result (Seen {\"\"}), resort to old method", result);
retval = -1L;
}
}
if (retval == -1L) {
Long returnValue = sftpGetSize.invoke(getPath());
if (returnValue == null) {
LOG.error("Error obtaining size of folder over SFTP");
}
return returnValue == null ? 0L : returnValue;
}
return retval;
case SMB:
SmbFile smbFile = getSmbFile();
size = (smbFile != null) ? FileUtils.folderSize(smbFile) : 0L;
break;
case FILE:
case TRASH_BIN:
size = FileUtils.folderSize(getFile(), null);
break;
case ROOT:
HybridFileParcelable baseFile = generateBaseFileFromParent();
if (baseFile != null) size = baseFile.getSize();
break;
case OTG:
size = FileUtils.otgFolderSize(path, context);
break;
case DOCUMENT_FILE:
final AtomicLong totalBytes = new AtomicLong(0);
OTGUtil.getDocumentFiles(
SafRootHolder.getUriRoot(),
path,
context,
OpenMode.DOCUMENT_FILE,
file -> totalBytes.addAndGet(FileUtils.getBaseFileSize(file, context)));
break;
case DROPBOX:
case BOX:
case GDRIVE:
case ONEDRIVE:
size =
FileUtils.folderSizeCloud(
mode, dataUtils.getAccount(mode).getMetadata(CloudUtil.stripPath(mode, path)));
break;
case FTP:
default:
return 0l;
}
return size;
}
/** Gets usable i.e. free space of a device */
public long getUsableSpace() {
long size = 0L;
switch (mode) {
case SMB:
size =
Single.fromCallable(
(Callable<Long>)
() -> {
try {
SmbFile smbFile = getSmbFile();
return smbFile != null ? smbFile.getDiskFreeSpace() : 0L;
} catch (SmbException e) {
LOG.warn("failed to get usage space for smb file", e);
return 0L;
}
})
.subscribeOn(Schedulers.io())
.blockingGet();
break;
case FILE:
case ROOT:
case TRASH_BIN:
size = getFile().getUsableSpace();
break;
case DROPBOX:
case BOX:
case GDRIVE:
case ONEDRIVE:
SpaceAllocation spaceAllocation = dataUtils.getAccount(mode).getAllocation();
size = spaceAllocation.getTotal() - spaceAllocation.getUsed();
break;
case SFTP:
final Long returnValue =
SshClientUtils.execute(
new SFtpClientTemplate<Long>(path, true) {
@Override
public Long execute(@NonNull SFTPClient client) throws IOException {
try {
Statvfs.Response response =
new Statvfs.Response(
path,
client
.getSFTPEngine()
.request(
Statvfs.request(
client, NetCopyClientUtils.extractRemotePathFrom(path)))
.retrieve());
return response.diskFreeSpace();
} catch (SFTPException e) {
LOG.error("Error querying server", e);
return 0L;
} catch (Buffer.BufferException e) {
LOG.error("Error parsing reply", e);
return 0L;
}
}
});
if (returnValue == null) {
LOG.error("Error obtaining usable space over SFTP");
}
size = returnValue == null ? 0L : returnValue;
break;
case DOCUMENT_FILE:
size =
FileProperties.getDeviceStorageRemainingSpace(SafRootHolder.INSTANCE.getVolumeLabel());
break;
case FTP:
/*
* Quirk, or dirty trick.
*
* I think 99.9% FTP servers in this world will not report their disk's remaining space,
* simply because they are not Serv-U (using AVBL command) or IIS (extended LIST command on
* it own). But it doesn't make sense to simply block write to FTP servers either, hence
* this value Integer.MAX_VALUE = 2048MB, which should be suitable for 99% of the cases.
*
* File sizes bigger than this, either Android device (unless TV boxes) would have
* difficulty to handle, either client and server side. In that case I shall recommend you
* to send it in splits, or just move to better transmission mechanism, like WiFi Direct
* as provided by Amaze File Utilities ;)
*
* - TranceLove
*/
size = Integer.MAX_VALUE;
case OTG:
// TODO: Get free space from OTG when {@link DocumentFile} API adds support
break;
}
return size;
}
/** Gets total size of the disk */
public long getTotal(Context context) {
long size = 0l;
switch (mode) {
case SMB:
// TODO: Find total storage space of SMB when JCIFS adds support
try {
SmbFile smbFile = getSmbFile();
size = smbFile != null ? smbFile.getDiskFreeSpace() : 0L;
} catch (SmbException e) {
LOG.warn("failed to get total space for smb file", e);
}
break;
case FILE:
case ROOT:
case TRASH_BIN:
size = getFile().getTotalSpace();
break;
case DROPBOX:
case BOX:
case ONEDRIVE:
case GDRIVE:
SpaceAllocation spaceAllocation = dataUtils.getAccount(mode).getAllocation();
size = spaceAllocation.getTotal();
break;
case SFTP:
final Long returnValue =
SshClientUtils.execute(
new SFtpClientTemplate<Long>(path, true) {
@Override
public Long execute(@NonNull SFTPClient client) throws IOException {
try {
Statvfs.Response response =
new Statvfs.Response(
path,
client
.getSFTPEngine()
.request(
Statvfs.request(
client, NetCopyClientUtils.extractRemotePathFrom(path)))
.retrieve());
return response.diskSize();
} catch (SFTPException e) {
LOG.error("Error querying server", e);
return 0L;
} catch (Buffer.BufferException e) {
LOG.error("Error parsing reply", e);
return 0L;
}
}
});
if (returnValue == null) {
LOG.error("Error obtaining total space over SFTP");
}
size = returnValue == null ? 0L : returnValue;
break;
case OTG:
// TODO: Find total storage space of OTG when {@link DocumentFile} API adds support
DocumentFile documentFile = OTGUtil.getDocumentFile(path, context, false);
size = documentFile.length();
break;
case DOCUMENT_FILE:
size = getDocumentFile(false).length();
break;
case FTP:
size = 0L;
}
return size;
}
/** Helper method to list children of this file */
public void forEachChildrenFile(Context context, boolean isRoot, OnFileFound onFileFound) {
switch (mode) {
case SFTP:
SshClientUtils.execute(
new SFtpClientTemplate<Boolean>(getPath(), true) {
@Override
public Boolean execute(@NonNull SFTPClient client) {
try {
for (RemoteResourceInfo info :
client.ls(NetCopyClientUtils.extractRemotePathFrom(getPath()))) {
boolean isDirectory = false;
try {
isDirectory = SshClientUtils.isDirectory(client, info);
} catch (IOException ifBrokenSymlink) {
LOG.warn("IOException checking isDirectory(): " + info.getPath());
continue;
}
HybridFileParcelable f = new HybridFileParcelable(getPath(), isDirectory, info);
onFileFound.onFileFound(f);
}
} catch (IOException e) {
LOG.warn("IOException", e);
AppConfig.toast(
context,
context.getString(
R.string.cannot_read_directory,
parseAndFormatUriForDisplay(getPath()),
e.getMessage()));
}
return true;
}
});
break;
case SMB:
try {
SmbFile smbFile = getSmbFile();
if (smbFile != null) {
for (SmbFile smbFile1 : smbFile.listFiles()) {
HybridFileParcelable baseFile;
try {
SmbFile sf = new SmbFile(smbFile1.getURL(), smbFile.getContext());
baseFile = new HybridFileParcelable(sf);