FileStorageUtils.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. @Nullable String fileName,
  149. long dateTaken,
  150. Boolean subfolderByDate) {
  151. String subPath = "";
  152. if (subfolderByDate) {
  153. subPath = getSubPathFromDate(dateTaken, current);
  154. }
  155. // Path must be normalized; otherwise the next RefreshFolderOperation has a mismatch and deletes the local file.
  156. return (remotePath + OCFile.PATH_SEPARATOR + subPath + (fileName == null ? "" : fileName))
  157. .replaceAll(OCFile.PATH_SEPARATOR + "+", OCFile.PATH_SEPARATOR);
  158. }
  159. public static String getParentPath(String remotePath) {
  160. String parentPath = new File(remotePath).getParent();
  161. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  162. return parentPath;
  163. }
  164. /**
  165. * Creates and populates a new {@link OCFile} object with the data read from the server.
  166. *
  167. * @param remote remote file read from the server (remote file or folder).
  168. * @return New OCFile instance representing the remote resource described by remote.
  169. */
  170. public static OCFile fillOCFile(RemoteFile remote) {
  171. OCFile file = new OCFile(remote.getRemotePath());
  172. file.setCreationTimestamp(remote.getCreationTimestamp());
  173. if (MimeType.DIRECTORY.equalsIgnoreCase(remote.getMimeType())) {
  174. file.setFileLength(remote.getSize());
  175. } else {
  176. file.setFileLength(remote.getLength());
  177. }
  178. file.setMimeType(remote.getMimeType());
  179. file.setModificationTimestamp(remote.getModifiedTimestamp());
  180. file.setEtag(remote.getEtag());
  181. file.setPermissions(remote.getPermissions());
  182. file.setRemoteId(remote.getRemoteId());
  183. file.setFavorite(remote.isFavorite());
  184. if (file.isFolder()) {
  185. file.setEncrypted(remote.isEncrypted());
  186. }
  187. file.setMountType(remote.getMountType());
  188. file.setPreviewAvailable(remote.isHasPreview());
  189. file.setUnreadCommentsCount(remote.getUnreadCommentsCount());
  190. file.setOwnerId(remote.getOwnerId());
  191. file.setOwnerDisplayName(remote.getOwnerDisplayName());
  192. file.setNote(remote.getNote());
  193. file.setSharees(new ArrayList<>(Arrays.asList(remote.getSharees())));
  194. return file;
  195. }
  196. /**
  197. * Creates and populates a new {@link RemoteFile} object with the data read from an {@link OCFile}.
  198. *
  199. * @param ocFile OCFile
  200. * @return New RemoteFile instance representing the resource described by ocFile.
  201. */
  202. public static RemoteFile fillRemoteFile(OCFile ocFile) {
  203. RemoteFile file = new RemoteFile(ocFile.getRemotePath());
  204. file.setCreationTimestamp(ocFile.getCreationTimestamp());
  205. file.setLength(ocFile.getFileLength());
  206. file.setMimeType(ocFile.getMimeType());
  207. file.setModifiedTimestamp(ocFile.getModificationTimestamp());
  208. file.setEtag(ocFile.getEtag());
  209. file.setPermissions(ocFile.getPermissions());
  210. file.setRemoteId(ocFile.getRemoteId());
  211. file.setFavorite(ocFile.isFavorite());
  212. return file;
  213. }
  214. public static List<OCFile> sortOcFolderDescDateModifiedWithoutFavoritesFirst(List<OCFile> files) {
  215. final int multiplier = -1;
  216. Collections.sort(files, (o1, o2) -> {
  217. @SuppressFBWarnings(value = "Bx", justification = "Would require stepping up API level")
  218. Long obj1 = o1.getModificationTimestamp();
  219. return multiplier * obj1.compareTo(o2.getModificationTimestamp());
  220. });
  221. return files;
  222. }
  223. public static List<OCFile> sortOcFolderDescDateModified(List<OCFile> files) {
  224. files = sortOcFolderDescDateModifiedWithoutFavoritesFirst(files);
  225. return FileSortOrder.sortCloudFilesByFavourite(files);
  226. }
  227. /**
  228. * Local Folder size.
  229. *
  230. * @param dir File
  231. * @return Size in bytes
  232. */
  233. public static long getFolderSize(File dir) {
  234. if (dir.exists() && dir.isDirectory()) {
  235. File[] files = dir.listFiles();
  236. if (files != null) {
  237. long result = 0;
  238. for (File f : files) {
  239. if (f.isDirectory()) {
  240. result += getFolderSize(f);
  241. } else {
  242. result += f.length();
  243. }
  244. }
  245. return result;
  246. }
  247. }
  248. return 0;
  249. }
  250. /**
  251. * Mimetype String of a file.
  252. *
  253. * @param path the file path
  254. * @return the mime type based on the file name
  255. */
  256. public static String getMimeTypeFromName(String path) {
  257. String extension = "";
  258. int pos = path.lastIndexOf('.');
  259. if (pos >= 0) {
  260. extension = path.substring(pos + 1);
  261. }
  262. String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.ROOT));
  263. return (result != null) ? result : "";
  264. }
  265. /**
  266. * Scans the default location for saving local copies of files searching for
  267. * a 'lost' file with the same full name as the {@link OCFile} received as
  268. * parameter.
  269. *
  270. * This method helps to keep linked local copies of the files when the app is uninstalled, and then
  271. * reinstalled in the device. OR after the cache of the app was deleted in system settings.
  272. *
  273. * The method is assuming that all the local changes in the file where synchronized in the past. This is dangerous,
  274. * but assuming the contrary could lead to massive unnecessary synchronizations of downloaded file after deleting
  275. * the app cache.
  276. *
  277. * This should be changed in the near future to avoid any chance of data loss, but we need to add some options
  278. * to limit hard automatic synchronizations to wifi, unless the user wants otherwise.
  279. *
  280. * @param file File to associate a possible 'lost' local file.
  281. * @param account Account holding file.
  282. */
  283. public static void searchForLocalFileInDefaultPath(OCFile file, Account account) {
  284. if (file.getStoragePath() == null && !file.isFolder()) {
  285. File f = new File(FileStorageUtils.getDefaultSavePathFor(account.name, file));
  286. if (f.exists()) {
  287. file.setStoragePath(f.getAbsolutePath());
  288. file.setLastSyncDateForData(f.lastModified());
  289. }
  290. }
  291. }
  292. @SuppressFBWarnings(value="OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE",
  293. justification="False-positive on the output stream")
  294. public static boolean copyFile(File src, File target) {
  295. boolean ret = true;
  296. InputStream in = null;
  297. OutputStream out = null;
  298. try {
  299. in = new FileInputStream(src);
  300. out = new FileOutputStream(target);
  301. byte[] buf = new byte[1024];
  302. int len;
  303. while ((len = in.read(buf)) > 0) {
  304. out.write(buf, 0, len);
  305. }
  306. } catch (IOException ex) {
  307. ret = false;
  308. } finally {
  309. if (in != null) {
  310. try {
  311. in.close();
  312. } catch (IOException e) {
  313. Log_OC.e(TAG, "Error closing input stream during copy", e);
  314. }
  315. }
  316. if (out != null) {
  317. try {
  318. out.close();
  319. } catch (IOException e) {
  320. Log_OC.e(TAG, "Error closing output stream during copy", e);
  321. }
  322. }
  323. }
  324. return ret;
  325. }
  326. public static boolean moveFile(File sourceFile, File targetFile) {
  327. if (copyFile(sourceFile, targetFile)) {
  328. return sourceFile.delete();
  329. } else {
  330. return false;
  331. }
  332. }
  333. public static boolean copyDirs(File sourceFolder, File targetFolder) {
  334. if (!targetFolder.mkdirs()) {
  335. return false;
  336. }
  337. for (File f : sourceFolder.listFiles()) {
  338. if (f.isDirectory()) {
  339. if (!copyDirs(f, new File(targetFolder, f.getName()))) {
  340. return false;
  341. }
  342. } else if (!FileStorageUtils.copyFile(f, new File(targetFolder, f.getName()))) {
  343. return false;
  344. }
  345. }
  346. return true;
  347. }
  348. public static void deleteRecursively(File file, FileDataStorageManager storageManager) {
  349. if (file.isDirectory()) {
  350. for (File child : file.listFiles()) {
  351. deleteRecursively(child, storageManager);
  352. }
  353. }
  354. storageManager.deleteFileInMediaScan(file.getAbsolutePath());
  355. file.delete();
  356. }
  357. public static boolean deleteRecursive(File file) {
  358. boolean res = true;
  359. if (file.isDirectory()) {
  360. for (File c : file.listFiles()) {
  361. res = deleteRecursive(c) && res;
  362. }
  363. }
  364. return file.delete() && res;
  365. }
  366. public static void checkIfFileFinishedSaving(OCFile file) {
  367. long lastModified = 0;
  368. long lastSize = 0;
  369. File realFile = new File(file.getStoragePath());
  370. if (realFile.lastModified() != file.getModificationTimestamp() && realFile.length() != file.getFileLength()) {
  371. while (realFile.lastModified() != lastModified && realFile.length() != lastSize) {
  372. lastModified = realFile.lastModified();
  373. lastSize = realFile.length();
  374. try {
  375. Thread.sleep(1000);
  376. } catch (InterruptedException e) {
  377. Log.d(TAG, "Failed to sleep for a bit");
  378. }
  379. }
  380. }
  381. }
  382. /**
  383. * Checks and returns true if file itself or ancestor is encrypted
  384. *
  385. * @param file file to check
  386. * @param storageManager up to date reference to storage manager
  387. * @return true if file itself or ancestor is encrypted
  388. */
  389. public static boolean checkEncryptionStatus(OCFile file, FileDataStorageManager storageManager) {
  390. if (file.isEncrypted()) {
  391. return true;
  392. }
  393. while (!OCFile.ROOT_PATH.equals(file.getRemotePath())) {
  394. if (file.isEncrypted()) {
  395. return true;
  396. }
  397. file = storageManager.getFileById(file.getParentId());
  398. }
  399. return false;
  400. }
  401. /**
  402. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/54652548223d151f089bdc6fc868b13ca5ab20a9/app/src
  403. * /main/java/com/amaze/filemanager/activities/MainActivity.java#L620 on 14.02.2019
  404. */
  405. @SuppressFBWarnings(value = "DMI_HARDCODED_ABSOLUTE_FILENAME",
  406. justification = "Default Android fallback storage path")
  407. public static List<String> getStorageDirectories(Activity activity) {
  408. // Final set of paths
  409. final List<String> rv = new ArrayList<>();
  410. // Primary physical SD-CARD (not emulated)
  411. final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
  412. // All Secondary SD-CARDs (all exclude primary) separated by ":"
  413. final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
  414. // Primary emulated SD-CARD
  415. final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
  416. if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
  417. // Device has physical external storage; use plain paths.
  418. if (TextUtils.isEmpty(rawExternalStorage)) {
  419. // EXTERNAL_STORAGE undefined; falling back to default.
  420. // Check for actual existence of the directory before adding to list
  421. if (new File(DEFAULT_FALLBACK_STORAGE_PATH).exists()) {
  422. rv.add(DEFAULT_FALLBACK_STORAGE_PATH);
  423. } else {
  424. //We know nothing else, use Environment's fallback
  425. rv.add(Environment.getExternalStorageDirectory().getAbsolutePath());
  426. }
  427. } else {
  428. rv.add(rawExternalStorage);
  429. }
  430. } else {
  431. // Device has emulated storage; external storage paths should have
  432. // userId burned into them.
  433. final String rawUserId;
  434. if (SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
  435. rawUserId = "";
  436. } else {
  437. final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
  438. final String[] folders = OCFile.PATH_SEPARATOR.split(path);
  439. final String lastFolder = folders[folders.length - 1];
  440. boolean isDigit = false;
  441. try {
  442. Integer.valueOf(lastFolder);
  443. isDigit = true;
  444. } catch (NumberFormatException ignored) {
  445. }
  446. rawUserId = isDigit ? lastFolder : "";
  447. }
  448. // /storage/emulated/0[1,2,...]
  449. if (TextUtils.isEmpty(rawUserId)) {
  450. rv.add(rawEmulatedStorageTarget);
  451. } else {
  452. rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
  453. }
  454. }
  455. // Add all secondary storages
  456. if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
  457. // All Secondary SD-CARDs splited into array
  458. final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
  459. Collections.addAll(rv, rawSecondaryStorages);
  460. }
  461. if (SDK_INT >= Build.VERSION_CODES.M && checkStoragePermission(activity)) {
  462. rv.clear();
  463. }
  464. if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
  465. String strings[] = getExtSdCardPathsForActivity(activity);
  466. File f;
  467. for (String s : strings) {
  468. f = new File(s);
  469. if (!rv.contains(s) && canListFiles(f)) {
  470. rv.add(s);
  471. }
  472. }
  473. }
  474. return rv;
  475. }
  476. /**
  477. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/d11e0d2874c6067910e58e059859431a31ad6aee/app/src
  478. * /main/java/com/amaze/filemanager/activities/superclasses/PermissionsActivity.java#L47 on
  479. * 14.02.2019
  480. */
  481. private static boolean checkStoragePermission(Activity activity) {
  482. // Verify that all required contact permissions have been granted.
  483. return ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
  484. == PackageManager.PERMISSION_GRANTED;
  485. }
  486. /**
  487. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/616f2a696823ab0e64ea7a017602dc08e783162e/app/src
  488. * /main/java/com/amaze/filemanager/filesystem/FileUtil.java#L764 on 14.02.2019
  489. */
  490. @TargetApi(Build.VERSION_CODES.KITKAT)
  491. private static String[] getExtSdCardPathsForActivity(Context context) {
  492. List<String> paths = new ArrayList<>();
  493. for (File file : context.getExternalFilesDirs("external")) {
  494. if (file != null) {
  495. int index = file.getAbsolutePath().lastIndexOf("/Android/data");
  496. if (index < 0) {
  497. Log_OC.w(TAG, "Unexpected external file dir: " + file.getAbsolutePath());
  498. } else {
  499. String path = file.getAbsolutePath().substring(0, index);
  500. try {
  501. path = new File(path).getCanonicalPath();
  502. } catch (IOException e) {
  503. // Keep non-canonical path.
  504. }
  505. paths.add(path);
  506. }
  507. }
  508. }
  509. if (paths.isEmpty()) {
  510. paths.add("/storage/sdcard1");
  511. }
  512. return paths.toArray(new String[0]);
  513. }
  514. /**
  515. * Taken from https://github.com/TeamAmaze/AmazeFileManager/blob/9cf1fd5ff1653c692cb54cf6bc71b572c19a11cd/app/src
  516. * /main/java/com/amaze/filemanager/utils/files/FileUtils.java#L754 on 14.02.2019
  517. */
  518. private static boolean canListFiles(File f) {
  519. return f.canRead() && f.isDirectory();
  520. }
  521. }