FileStorageUtils.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2016 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.owncloud.android.utils;
  20. import android.Manifest;
  21. import android.accounts.Account;
  22. import android.content.Context;
  23. import android.content.pm.PackageManager;
  24. import android.content.res.Resources;
  25. import android.net.Uri;
  26. import android.os.Build;
  27. import android.os.Environment;
  28. import android.text.TextUtils;
  29. import android.util.Log;
  30. import android.webkit.MimeTypeMap;
  31. import com.nextcloud.client.account.User;
  32. import com.owncloud.android.MainApp;
  33. import com.owncloud.android.R;
  34. import com.owncloud.android.datamodel.FileDataStorageManager;
  35. import com.owncloud.android.datamodel.OCFile;
  36. import com.owncloud.android.lib.common.utils.Log_OC;
  37. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  38. import java.io.File;
  39. import java.io.FileInputStream;
  40. import java.io.FileOutputStream;
  41. import java.io.IOException;
  42. import java.io.InputStream;
  43. import java.io.OutputStream;
  44. import java.text.DateFormat;
  45. import java.text.SimpleDateFormat;
  46. import java.util.ArrayList;
  47. import java.util.Arrays;
  48. import java.util.Collection;
  49. import java.util.Collections;
  50. import java.util.Date;
  51. import java.util.HashSet;
  52. import java.util.List;
  53. import java.util.Locale;
  54. import java.util.TimeZone;
  55. import javax.annotation.Nullable;
  56. import androidx.core.app.ActivityCompat;
  57. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  58. import static android.os.Build.VERSION.SDK_INT;
  59. /**
  60. * Static methods to help in access to local file system.
  61. */
  62. public final class FileStorageUtils {
  63. private static final String TAG = FileStorageUtils.class.getSimpleName();
  64. private static final String PATTERN_YYYY_MM = "yyyy/MM/";
  65. private static final String DEFAULT_FALLBACK_STORAGE_PATH = "/storage/sdcard0";
  66. private FileStorageUtils() {
  67. // utility class -> private constructor
  68. }
  69. /**
  70. * Get local owncloud storage path for accountName.
  71. */
  72. public static String getSavePath(String accountName) {
  73. return MainApp.getStoragePath()
  74. + File.separator
  75. + MainApp.getDataFolder()
  76. + File.separator
  77. + Uri.encode(accountName, "@");
  78. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  79. // that can be in the accountName since 0.1.190B
  80. }
  81. /**
  82. * Get local path where OCFile file is to be stored after upload. That is,
  83. * corresponding local path (in local owncloud storage) to remote uploaded
  84. * file.
  85. */
  86. public static String getDefaultSavePathFor(String accountName, OCFile file) {
  87. return getSavePath(accountName) + file.getDecryptedRemotePath();
  88. }
  89. /**
  90. * Get absolute path to tmp folder inside datafolder in sd-card for given accountName.
  91. */
  92. public static String getTemporalPath(String accountName) {
  93. return MainApp.getStoragePath()
  94. + File.separator
  95. + MainApp.getDataFolder()
  96. + File.separator
  97. + "tmp"
  98. + File.separator
  99. + Uri.encode(accountName, "@");
  100. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  101. // that can be in the accountName since 0.1.190B
  102. }
  103. /**
  104. * Get absolute path to tmp folder inside app folder for given accountName.
  105. */
  106. public static String getInternalTemporalPath(String accountName, Context context) {
  107. return context.getFilesDir()
  108. + File.separator
  109. + MainApp.getDataFolder()
  110. + File.separator
  111. + "tmp"
  112. + File.separator
  113. + Uri.encode(accountName, "@");
  114. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  115. // that can be in the accountName since 0.1.190B
  116. }
  117. /**
  118. * Optimistic number of bytes available on sd-card. accountName is ignored.
  119. *
  120. * @return Optimistic number of available bytes (can be less)
  121. */
  122. public static long getUsableSpace() {
  123. File savePath = new File(MainApp.getStoragePath());
  124. return savePath.getUsableSpace();
  125. }
  126. /**
  127. * Returns the a string like 2016/08/ for the passed date. If date is 0 an empty
  128. * string is returned
  129. *
  130. * @param date: date in microseconds since 1st January 1970
  131. * @return string: yyyy/mm/
  132. */
  133. private static String getSubPathFromDate(long date, Locale currentLocale) {
  134. if (date == 0) {
  135. return "";
  136. }
  137. Date d = new Date(date);
  138. DateFormat df = new SimpleDateFormat(PATTERN_YYYY_MM, currentLocale);
  139. df.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
  140. return df.format(d);
  141. }
  142. /**
  143. * Returns the InstantUploadFilePath on the nextcloud instance
  144. *
  145. * @param dateTaken: Time in milliseconds since 1970 when the picture was taken.
  146. * @return instantUpload path, eg. /Camera/2017/01/fileName
  147. */
  148. public static String getInstantUploadFilePath(File file,
  149. Locale current,
  150. String remotePath,
  151. String syncedFolderLocalPath,
  152. long dateTaken,
  153. Boolean subfolderByDate) {
  154. String subfolderByDatePath = "";
  155. if (subfolderByDate) {
  156. subfolderByDatePath = getSubPathFromDate(dateTaken, current);
  157. }
  158. File parentFile = new File(file.getAbsolutePath().replace(syncedFolderLocalPath, "")).getParentFile();
  159. String relativeSubfolderPath = "";
  160. if (parentFile == null) {
  161. Log_OC.e("AutoUpload", "Parent folder does not exists!");
  162. } else {
  163. relativeSubfolderPath = parentFile.getAbsolutePath();
  164. }
  165. // Path must be normalized; otherwise the next RefreshFolderOperation has a mismatch and deletes the local file.
  166. return (remotePath +
  167. OCFile.PATH_SEPARATOR +
  168. subfolderByDatePath +
  169. OCFile.PATH_SEPARATOR +
  170. relativeSubfolderPath +
  171. OCFile.PATH_SEPARATOR +
  172. file.getName())
  173. .replaceAll(OCFile.PATH_SEPARATOR + "+", OCFile.PATH_SEPARATOR);
  174. }
  175. public static String getParentPath(String remotePath) {
  176. String parentPath = new File(remotePath).getParent();
  177. if (parentPath != null) {
  178. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  179. }
  180. return parentPath;
  181. }
  182. /**
  183. * Creates and populates a new {@link OCFile} object with the data read from the server.
  184. *
  185. * @param remote remote file read from the server (remote file or folder).
  186. * @return New OCFile instance representing the remote resource described by remote.
  187. */
  188. public static OCFile fillOCFile(RemoteFile remote) {
  189. OCFile file = new OCFile(remote.getRemotePath());
  190. file.setDecryptedRemotePath(remote.getRemotePath());
  191. file.setCreationTimestamp(remote.getCreationTimestamp());
  192. if (MimeType.DIRECTORY.equalsIgnoreCase(remote.getMimeType())) {
  193. file.setFileLength(remote.getSize());
  194. } else {
  195. file.setFileLength(remote.getLength());
  196. }
  197. file.setMimeType(remote.getMimeType());
  198. file.setModificationTimestamp(remote.getModifiedTimestamp());
  199. file.setEtag(remote.getEtag());
  200. file.setPermissions(remote.getPermissions());
  201. file.setRemoteId(remote.getRemoteId());
  202. file.setFavorite(remote.isFavorite());
  203. if (file.isFolder()) {
  204. file.setEncrypted(remote.isEncrypted());
  205. }
  206. file.setMountType(remote.getMountType());
  207. file.setPreviewAvailable(remote.isHasPreview());
  208. file.setUnreadCommentsCount(remote.getUnreadCommentsCount());
  209. file.setOwnerId(remote.getOwnerId());
  210. file.setOwnerDisplayName(remote.getOwnerDisplayName());
  211. file.setNote(remote.getNote());
  212. file.setSharees(new ArrayList<>(Arrays.asList(remote.getSharees())));
  213. file.setRichWorkspace(remote.getRichWorkspace());
  214. return file;
  215. }
  216. /**
  217. * Creates and populates a new {@link RemoteFile} object with the data read from an {@link OCFile}.
  218. *
  219. * @param ocFile OCFile
  220. * @return New RemoteFile instance representing the resource described by ocFile.
  221. */
  222. public static RemoteFile fillRemoteFile(OCFile ocFile) {
  223. RemoteFile file = new RemoteFile(ocFile.getRemotePath());
  224. file.setCreationTimestamp(ocFile.getCreationTimestamp());
  225. file.setLength(ocFile.getFileLength());
  226. file.setMimeType(ocFile.getMimeType());
  227. file.setModifiedTimestamp(ocFile.getModificationTimestamp());
  228. file.setEtag(ocFile.getEtag());
  229. file.setPermissions(ocFile.getPermissions());
  230. file.setRemoteId(ocFile.getRemoteId());
  231. file.setFavorite(ocFile.isFavorite());
  232. return file;
  233. }
  234. public static List<OCFile> sortOcFolderDescDateModifiedWithoutFavoritesFirst(List<OCFile> files) {
  235. final int multiplier = -1;
  236. Collections.sort(files, (o1, o2) -> {
  237. return multiplier * Long.compare(o1.getModificationTimestamp(),o2.getModificationTimestamp());
  238. });
  239. return files;
  240. }
  241. public static List<OCFile> sortOcFolderDescDateModified(List<OCFile> files) {
  242. files = sortOcFolderDescDateModifiedWithoutFavoritesFirst(files);
  243. return FileSortOrder.sortCloudFilesByFavourite(files);
  244. }
  245. /**
  246. * Local Folder size.
  247. *
  248. * @param dir File
  249. * @return Size in bytes
  250. */
  251. public static long getFolderSize(File dir) {
  252. if (dir.exists() && dir.isDirectory()) {
  253. File[] files = dir.listFiles();
  254. if (files != null) {
  255. long result = 0;
  256. for (File f : files) {
  257. if (f.isDirectory()) {
  258. result += getFolderSize(f);
  259. } else {
  260. result += f.length();
  261. }
  262. }
  263. return result;
  264. }
  265. }
  266. return 0;
  267. }
  268. /**
  269. * Mimetype String of a file.
  270. *
  271. * @param path the file path
  272. * @return the mime type based on the file name
  273. */
  274. public static String getMimeTypeFromName(String path) {
  275. String extension = "";
  276. int pos = path.lastIndexOf('.');
  277. if (pos >= 0) {
  278. extension = path.substring(pos + 1);
  279. }
  280. String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.ROOT));
  281. return (result != null) ? result : "";
  282. }
  283. /**
  284. * Scans the default location for saving local copies of files searching for
  285. * a 'lost' file with the same full name as the {@link OCFile} received as
  286. * parameter.
  287. *
  288. * This method helps to keep linked local copies of the files when the app is uninstalled, and then
  289. * reinstalled in the device. OR after the cache of the app was deleted in system settings.
  290. *
  291. * The method is assuming that all the local changes in the file where synchronized in the past. This is dangerous,
  292. * but assuming the contrary could lead to massive unnecessary synchronizations of downloaded file after deleting
  293. * the app cache.
  294. *
  295. * This should be changed in the near future to avoid any chance of data loss, but we need to add some options
  296. * to limit hard automatic synchronizations to wifi, unless the user wants otherwise.
  297. *
  298. * @param file File to associate a possible 'lost' local file.
  299. * @param accountName File owner account name.
  300. */
  301. public static void searchForLocalFileInDefaultPath(OCFile file, String accountName) {
  302. if ((file.getStoragePath() == null || !new File(file.getStoragePath()).exists()) && !file.isFolder()) {
  303. File f = new File(FileStorageUtils.getDefaultSavePathFor(accountName, file));
  304. if (f.exists()) {
  305. file.setStoragePath(f.getAbsolutePath());
  306. file.setLastSyncDateForData(f.lastModified());
  307. }
  308. }
  309. }
  310. @SuppressFBWarnings(value="OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE",
  311. justification="False-positive on the output stream")
  312. public static boolean copyFile(File src, File target) {
  313. boolean ret = true;
  314. InputStream in = null;
  315. OutputStream out = null;
  316. try {
  317. in = new FileInputStream(src);
  318. out = new FileOutputStream(target);
  319. byte[] buf = new byte[1024];
  320. int len;
  321. while ((len = in.read(buf)) > 0) {
  322. out.write(buf, 0, len);
  323. }
  324. } catch (IOException ex) {
  325. ret = false;
  326. } finally {
  327. if (in != null) {
  328. try {
  329. in.close();
  330. } catch (IOException e) {
  331. Log_OC.e(TAG, "Error closing input stream during copy", e);
  332. }
  333. }
  334. if (out != null) {
  335. try {
  336. out.close();
  337. } catch (IOException e) {
  338. Log_OC.e(TAG, "Error closing output stream during copy", e);
  339. }
  340. }
  341. }
  342. return ret;
  343. }
  344. public static boolean moveFile(File sourceFile, File targetFile) {
  345. if (copyFile(sourceFile, targetFile)) {
  346. return sourceFile.delete();
  347. } else {
  348. return false;
  349. }
  350. }
  351. public static boolean copyDirs(File sourceFolder, File targetFolder) {
  352. if (!targetFolder.mkdirs()) {
  353. return false;
  354. }
  355. for (File f : sourceFolder.listFiles()) {
  356. if (f.isDirectory()) {
  357. if (!copyDirs(f, new File(targetFolder, f.getName()))) {
  358. return false;
  359. }
  360. } else if (!FileStorageUtils.copyFile(f, new File(targetFolder, f.getName()))) {
  361. return false;
  362. }
  363. }
  364. return true;
  365. }
  366. public static void deleteRecursively(File file, FileDataStorageManager storageManager) {
  367. if (file.isDirectory()) {
  368. for (File child : file.listFiles()) {
  369. deleteRecursively(child, storageManager);
  370. }
  371. }
  372. storageManager.deleteFileInMediaScan(file.getAbsolutePath());
  373. file.delete();
  374. }
  375. public static boolean deleteRecursive(File file) {
  376. boolean res = true;
  377. if (file.isDirectory()) {
  378. for (File c : file.listFiles()) {
  379. res = deleteRecursive(c) && res;
  380. }
  381. }
  382. return file.delete() && res;
  383. }
  384. public static void checkIfFileFinishedSaving(OCFile file) {
  385. long lastModified = 0;
  386. long lastSize = 0;
  387. File realFile = new File(file.getStoragePath());
  388. if (realFile.lastModified() != file.getModificationTimestamp() && realFile.length() != file.getFileLength()) {
  389. while (realFile.lastModified() != lastModified && realFile.length() != lastSize) {
  390. lastModified = realFile.lastModified();
  391. lastSize = realFile.length();
  392. try {
  393. Thread.sleep(1000);
  394. } catch (InterruptedException e) {
  395. Log.d(TAG, "Failed to sleep for a bit");
  396. }
  397. }
  398. }
  399. }
  400. /**
  401. * Checks and returns true if file itself or ancestor is encrypted
  402. *
  403. * @param file file to check
  404. * @param storageManager up to date reference to storage manager
  405. * @return true if file itself or ancestor is encrypted
  406. */
  407. public static boolean checkEncryptionStatus(OCFile file, FileDataStorageManager storageManager) {
  408. if (file.isEncrypted()) {
  409. return true;
  410. }
  411. while (!OCFile.ROOT_PATH.equals(file.getDecryptedRemotePath())) {
  412. if (file.isEncrypted()) {
  413. return true;
  414. }
  415. file = storageManager.getFileById(file.getParentId());
  416. }
  417. return false;
  418. }
  419. /**
  420. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/54652548223d151f089bdc6fc868b13ca5ab20a9/app/src
  421. * /main/java/com/amaze/filemanager/activities/MainActivity.java#L620 on 14.02.2019
  422. */
  423. @SuppressFBWarnings(value = "DMI_HARDCODED_ABSOLUTE_FILENAME",
  424. justification = "Default Android fallback storage path")
  425. public static List<String> getStorageDirectories(Context context) {
  426. // Final set of paths
  427. final List<String> rv = new ArrayList<>();
  428. // Primary physical SD-CARD (not emulated)
  429. final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
  430. // All Secondary SD-CARDs (all exclude primary) separated by ":"
  431. final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
  432. // Primary emulated SD-CARD
  433. final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
  434. if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
  435. // Device has physical external storage; use plain paths.
  436. if (TextUtils.isEmpty(rawExternalStorage)) {
  437. // EXTERNAL_STORAGE undefined; falling back to default.
  438. // Check for actual existence of the directory before adding to list
  439. if (new File(DEFAULT_FALLBACK_STORAGE_PATH).exists()) {
  440. rv.add(DEFAULT_FALLBACK_STORAGE_PATH);
  441. } else {
  442. //We know nothing else, use Environment's fallback
  443. rv.add(Environment.getExternalStorageDirectory().getAbsolutePath());
  444. }
  445. } else {
  446. rv.add(rawExternalStorage);
  447. }
  448. } else {
  449. // Device has emulated storage; external storage paths should have
  450. // userId burned into them.
  451. final String rawUserId;
  452. final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
  453. final String[] folders = OCFile.PATH_SEPARATOR.split(path);
  454. final String lastFolder = folders[folders.length - 1];
  455. boolean isDigit = false;
  456. try {
  457. Integer.valueOf(lastFolder);
  458. isDigit = true;
  459. } catch (NumberFormatException ignored) {
  460. }
  461. rawUserId = isDigit ? lastFolder : "";
  462. // /storage/emulated/0[1,2,...]
  463. if (TextUtils.isEmpty(rawUserId)) {
  464. rv.add(rawEmulatedStorageTarget);
  465. } else {
  466. rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
  467. }
  468. }
  469. // Add all secondary storages
  470. if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
  471. // All Secondary SD-CARDs splited into array
  472. final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
  473. Collections.addAll(rv, rawSecondaryStorages);
  474. }
  475. if (SDK_INT >= Build.VERSION_CODES.M && checkStoragePermission(context)) {
  476. rv.clear();
  477. }
  478. String[] extSdCardPaths = getExtSdCardPathsForActivity(context);
  479. File f;
  480. for (String extSdCardPath : extSdCardPaths) {
  481. f = new File(extSdCardPath);
  482. if (!rv.contains(extSdCardPath) && canListFiles(f)) {
  483. rv.add(extSdCardPath);
  484. }
  485. }
  486. return rv;
  487. }
  488. /**
  489. * Update the local path summary display. If a special directory is recognized, it is replaced by its name.
  490. * <p>
  491. * Example: /storage/emulated/0/Movies -> Internal Storage / Movies Example: /storage/ABC/non/standard/directory ->
  492. * ABC /non/standard/directory
  493. *
  494. * @param path the path to display
  495. * @return a user friendly path as defined in examples, or {@param path} if the storage device isn't recognized.
  496. */
  497. public static String pathToUserFriendlyDisplay(String path, Context context, Resources resources) {
  498. // Determine storage device (external, sdcard...)
  499. String storageDevice = null;
  500. for (String storageDirectory : FileStorageUtils.getStorageDirectories(context)) {
  501. if (path.startsWith(storageDirectory)) {
  502. storageDevice = storageDirectory;
  503. break;
  504. }
  505. }
  506. // If storage device was not found, display full path
  507. if (storageDevice == null) {
  508. return path;
  509. }
  510. // Default to full path without storage device path
  511. String storageFolder;
  512. try {
  513. storageFolder = path.substring(storageDevice.length() + 1);
  514. } catch (StringIndexOutOfBoundsException e) {
  515. storageFolder = "";
  516. }
  517. FileStorageUtils.StandardDirectory standardDirectory = FileStorageUtils.StandardDirectory.fromPath(storageFolder);
  518. if (standardDirectory != null) { // Friendly name of standard directory
  519. storageFolder = " " + resources.getString(standardDirectory.getDisplayName());
  520. }
  521. // Shorten the storage device to a friendlier display name
  522. if (storageDevice.startsWith(Environment.getExternalStorageDirectory().getAbsolutePath())) {
  523. storageDevice = resources.getString(R.string.storage_internal_storage);
  524. } else {
  525. storageDevice = new File(storageDevice).getName();
  526. }
  527. return resources.getString(R.string.local_folder_friendly_path, storageDevice, storageFolder);
  528. }
  529. /**
  530. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/d11e0d2874c6067910e58e059859431a31ad6aee/app/src
  531. * /main/java/com/amaze/filemanager/activities/superclasses/PermissionsActivity.java#L47 on 14.02.2019
  532. */
  533. private static boolean checkStoragePermission(Context context) {
  534. // Verify that all required contact permissions have been granted.
  535. return ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
  536. == PackageManager.PERMISSION_GRANTED;
  537. }
  538. /**
  539. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/616f2a696823ab0e64ea7a017602dc08e783162e/app/src
  540. * /main/java/com/amaze/filemanager/filesystem/FileUtil.java#L764 on 14.02.2019
  541. */
  542. private static String[] getExtSdCardPathsForActivity(Context context) {
  543. List<String> paths = new ArrayList<>();
  544. for (File file : context.getExternalFilesDirs("external")) {
  545. if (file != null) {
  546. int index = file.getAbsolutePath().lastIndexOf("/Android/data");
  547. if (index < 0) {
  548. Log_OC.w(TAG, "Unexpected external file dir: " + file.getAbsolutePath());
  549. } else {
  550. String path = file.getAbsolutePath().substring(0, index);
  551. try {
  552. path = new File(path).getCanonicalPath();
  553. } catch (IOException e) {
  554. // Keep non-canonical path.
  555. }
  556. paths.add(path);
  557. }
  558. }
  559. }
  560. if (paths.isEmpty()) {
  561. paths.add("/storage/sdcard1");
  562. }
  563. return paths.toArray(new String[0]);
  564. }
  565. /**
  566. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/9cf1fd5ff1653c692cb54cf6bc71b572c19a11cd/app/src
  567. * /main/java/com/amaze/filemanager/utils/files/FileUtils.java#L754 on 14.02.2019
  568. */
  569. private static boolean canListFiles(File f) {
  570. return f.canRead() && f.isDirectory();
  571. }
  572. /**
  573. * Should be converted to an enum when we only support min SDK version for Environment.DIRECTORY_DOCUMENTS
  574. */
  575. public static class StandardDirectory {
  576. public static final StandardDirectory PICTURES = new StandardDirectory(
  577. Environment.DIRECTORY_PICTURES,
  578. R.string.storage_pictures,
  579. R.drawable.ic_image_grey600
  580. );
  581. public static final StandardDirectory CAMERA = new StandardDirectory(
  582. Environment.DIRECTORY_DCIM,
  583. R.string.storage_camera,
  584. R.drawable.ic_camera
  585. );
  586. public static final StandardDirectory DOCUMENTS;
  587. static {
  588. DOCUMENTS = new StandardDirectory(
  589. Environment.DIRECTORY_DOCUMENTS,
  590. R.string.storage_documents,
  591. R.drawable.ic_document_grey600
  592. );
  593. }
  594. public static final StandardDirectory DOWNLOADS = new StandardDirectory(
  595. Environment.DIRECTORY_DOWNLOADS,
  596. R.string.storage_downloads,
  597. R.drawable.ic_download_grey600
  598. );
  599. public static final StandardDirectory MOVIES = new StandardDirectory(
  600. Environment.DIRECTORY_MOVIES,
  601. R.string.storage_movies,
  602. R.drawable.ic_movie_grey600
  603. );
  604. public static final StandardDirectory MUSIC = new StandardDirectory(
  605. Environment.DIRECTORY_MUSIC,
  606. R.string.storage_music,
  607. R.drawable.ic_music_grey600
  608. );
  609. private final String name;
  610. private final int displayNameResource;
  611. private final int iconResource;
  612. private StandardDirectory(String name, int displayNameResource, int iconResource) {
  613. this.name = name;
  614. this.displayNameResource = displayNameResource;
  615. this.iconResource = iconResource;
  616. }
  617. public String getName() {
  618. return this.name;
  619. }
  620. public int getDisplayName() {
  621. return this.displayNameResource;
  622. }
  623. public int getIcon() {
  624. return this.iconResource;
  625. }
  626. public static Collection<StandardDirectory> getStandardDirectories() {
  627. Collection<StandardDirectory> standardDirectories = new HashSet<>();
  628. standardDirectories.add(PICTURES);
  629. standardDirectories.add(CAMERA);
  630. if (DOCUMENTS != null) {
  631. standardDirectories.add(DOCUMENTS);
  632. }
  633. standardDirectories.add(DOWNLOADS);
  634. standardDirectories.add(MOVIES);
  635. standardDirectories.add(MUSIC);
  636. return standardDirectories;
  637. }
  638. @Nullable
  639. public static StandardDirectory fromPath(String path) {
  640. for (StandardDirectory directory : getStandardDirectories()) {
  641. if (directory.getName().equals(path)) {
  642. return directory;
  643. }
  644. }
  645. return null;
  646. }
  647. }
  648. }