FileStorageUtils.java 27 KB

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