FileStorageUtils.java 22 KB

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