FileStorageUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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.accounts.Account;
  21. import android.net.Uri;
  22. import android.util.Log;
  23. import android.webkit.MimeTypeMap;
  24. import com.owncloud.android.MainApp;
  25. import com.owncloud.android.datamodel.FileDataStorageManager;
  26. import com.owncloud.android.datamodel.OCFile;
  27. import com.owncloud.android.lib.common.utils.Log_OC;
  28. import com.owncloud.android.lib.resources.files.RemoteFile;
  29. import java.io.File;
  30. import java.io.FileInputStream;
  31. import java.io.FileOutputStream;
  32. import java.io.IOException;
  33. import java.io.InputStream;
  34. import java.io.OutputStream;
  35. import java.text.DateFormat;
  36. import java.text.SimpleDateFormat;
  37. import java.util.Collections;
  38. import java.util.Date;
  39. import java.util.List;
  40. import java.util.Locale;
  41. import java.util.TimeZone;
  42. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  43. /**
  44. * Static methods to help in access to local file system.
  45. */
  46. public class FileStorageUtils {
  47. private static final String TAG = FileStorageUtils.class.getSimpleName();
  48. public static final String PATTERN_YYYY_MM = "yyyy/MM/";
  49. /**
  50. * Get local owncloud storage path for accountName.
  51. */
  52. public static String getSavePath(String accountName) {
  53. return MainApp.getStoragePath()
  54. + File.separator
  55. + MainApp.getDataFolder()
  56. + File.separator
  57. + Uri.encode(accountName, "@");
  58. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  59. // that can be in the accountName since 0.1.190B
  60. }
  61. /**
  62. * Get local path where OCFile file is to be stored after upload. That is,
  63. * corresponding local path (in local owncloud storage) to remote uploaded
  64. * file.
  65. */
  66. public static String getDefaultSavePathFor(String accountName, OCFile file) {
  67. return getSavePath(accountName) + file.getDecryptedRemotePath();
  68. }
  69. /**
  70. * Get absolute path to tmp folder inside datafolder in sd-card for given accountName.
  71. */
  72. public static String getTemporalPath(String accountName) {
  73. return MainApp.getStoragePath()
  74. + File.separator
  75. + MainApp.getDataFolder()
  76. + File.separator
  77. + "tmp"
  78. + File.separator
  79. + Uri.encode(accountName, "@");
  80. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  81. // that can be in the accountName since 0.1.190B
  82. }
  83. /**
  84. * Optimistic number of bytes available on sd-card. accountName is ignored.
  85. *
  86. * @return Optimistic number of available bytes (can be less)
  87. */
  88. public static long getUsableSpace() {
  89. File savePath = new File(MainApp.getStoragePath());
  90. return savePath.getUsableSpace();
  91. }
  92. /**
  93. * Returns the a string like 2016/08/ for the passed date. If date is 0 an empty
  94. * string is returned
  95. *
  96. * @param date: date in microseconds since 1st January 1970
  97. * @return string: yyyy/mm/
  98. */
  99. private static String getSubpathFromDate(long date, Locale currentLocale) {
  100. if (date == 0) {
  101. return "";
  102. }
  103. Date d = new Date(date);
  104. DateFormat df = new SimpleDateFormat(PATTERN_YYYY_MM, currentLocale);
  105. df.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
  106. return df.format(d);
  107. }
  108. /**
  109. * Returns the InstantUploadFilePath on the nextcloud instance
  110. *
  111. * @param fileName complete file name
  112. * @param dateTaken: Time in milliseconds since 1970 when the picture was taken.
  113. * @return instantUpload path, eg. /Camera/2017/01/fileName
  114. */
  115. public static String getInstantUploadFilePath(Locale current,
  116. String remotePath,
  117. String fileName,
  118. long dateTaken,
  119. Boolean subfolderByDate) {
  120. String subPath = "";
  121. if (subfolderByDate) {
  122. subPath = getSubpathFromDate(dateTaken, current);
  123. }
  124. return remotePath + OCFile.PATH_SEPARATOR + subPath + (fileName == null ? "" : fileName);
  125. }
  126. public static String getParentPath(String remotePath) {
  127. String parentPath = new File(remotePath).getParent();
  128. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  129. return parentPath;
  130. }
  131. /**
  132. * Creates and populates a new {@link OCFile} object with the data read from the server.
  133. *
  134. * @param remote remote file read from the server (remote file or folder).
  135. * @return New OCFile instance representing the remote resource described by remote.
  136. */
  137. public static OCFile fillOCFile(RemoteFile remote) {
  138. OCFile file = new OCFile(remote.getRemotePath());
  139. file.setCreationTimestamp(remote.getCreationTimestamp());
  140. if (MimeType.DIRECTORY.equalsIgnoreCase(remote.getMimeType())) {
  141. file.setFileLength(remote.getSize());
  142. } else {
  143. file.setFileLength(remote.getLength());
  144. }
  145. file.setMimetype(remote.getMimeType());
  146. file.setModificationTimestamp(remote.getModifiedTimestamp());
  147. file.setEtag(remote.getEtag());
  148. file.setPermissions(remote.getPermissions());
  149. file.setRemoteId(remote.getRemoteId());
  150. file.setFavorite(remote.getIsFavorite());
  151. if (file.isFolder()) {
  152. file.setEncrypted(remote.getIsEncrypted());
  153. }
  154. file.setMountType(remote.getMountType());
  155. return file;
  156. }
  157. /**
  158. * Creates and populates a new {@link RemoteFile} object with the data read from an {@link OCFile}.
  159. *
  160. * @param ocFile OCFile
  161. * @return New RemoteFile instance representing the resource described by ocFile.
  162. */
  163. public static RemoteFile fillRemoteFile(OCFile ocFile) {
  164. RemoteFile file = new RemoteFile(ocFile.getRemotePath());
  165. file.setCreationTimestamp(ocFile.getCreationTimestamp());
  166. file.setLength(ocFile.getFileLength());
  167. file.setMimeType(ocFile.getMimeType());
  168. file.setModifiedTimestamp(ocFile.getModificationTimestamp());
  169. file.setEtag(ocFile.getEtag());
  170. file.setPermissions(ocFile.getPermissions());
  171. file.setRemoteId(ocFile.getRemoteId());
  172. file.setFavorite(ocFile.getIsFavorite());
  173. return file;
  174. }
  175. public static List<OCFile> sortOcFolderDescDateModified(List<OCFile> files) {
  176. final int multiplier = -1;
  177. Collections.sort(files, (o1, o2) -> {
  178. @SuppressFBWarnings(value = "Bx", justification = "Would require stepping up API level")
  179. Long obj1 = o1.getModificationTimestamp();
  180. return multiplier * obj1.compareTo(o2.getModificationTimestamp());
  181. });
  182. return FileSortOrder.sortCloudFilesByFavourite(files);
  183. }
  184. /**
  185. * Local Folder size.
  186. *
  187. * @param dir File
  188. * @return Size in bytes
  189. */
  190. public static long getFolderSize(File dir) {
  191. if (dir.exists() && dir.isDirectory()) {
  192. File[] files = dir.listFiles();
  193. if (files != null) {
  194. long result = 0;
  195. for (File f : files) {
  196. if (f.isDirectory()) {
  197. result += getFolderSize(f);
  198. } else {
  199. result += f.length();
  200. }
  201. }
  202. return result;
  203. }
  204. }
  205. return 0;
  206. }
  207. /**
  208. * Mimetype String of a file.
  209. *
  210. * @param path the file path
  211. * @return the mime type based on the file name
  212. */
  213. public static String getMimeTypeFromName(String path) {
  214. String extension = "";
  215. int pos = path.lastIndexOf('.');
  216. if (pos >= 0) {
  217. extension = path.substring(pos + 1);
  218. }
  219. String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.ROOT));
  220. return (result != null) ? result : "";
  221. }
  222. /**
  223. * Scans the default location for saving local copies of files searching for
  224. * a 'lost' file with the same full name as the {@link OCFile} received as
  225. * parameter.
  226. *
  227. * This method helps to keep linked local copies of the files when the app is uninstalled, and then
  228. * reinstalled in the device. OR after the cache of the app was deleted in system settings.
  229. *
  230. * The method is assuming that all the local changes in the file where synchronized in the past. This is dangerous,
  231. * but assuming the contrary could lead to massive unnecessary synchronizations of downloaded file after deleting
  232. * the app cache.
  233. *
  234. * This should be changed in the near future to avoid any chance of data loss, but we need to add some options
  235. * to limit hard automatic synchronizations to wifi, unless the user wants otherwise.
  236. *
  237. * @param file File to associate a possible 'lost' local file.
  238. * @param account Account holding file.
  239. */
  240. public static void searchForLocalFileInDefaultPath(OCFile file, Account account) {
  241. if (file.getStoragePath() == null && !file.isFolder()) {
  242. File f = new File(FileStorageUtils.getDefaultSavePathFor(account.name, file));
  243. if (f.exists()) {
  244. file.setStoragePath(f.getAbsolutePath());
  245. file.setLastSyncDateForData(f.lastModified());
  246. }
  247. }
  248. }
  249. public static boolean copyFile(File src, File target) {
  250. boolean ret = true;
  251. InputStream in = null;
  252. OutputStream out = null;
  253. try {
  254. in = new FileInputStream(src);
  255. out = new FileOutputStream(target);
  256. byte[] buf = new byte[1024];
  257. int len;
  258. while ((len = in.read(buf)) > 0) {
  259. out.write(buf, 0, len);
  260. }
  261. } catch (IOException ex) {
  262. ret = false;
  263. } finally {
  264. if (in != null) {
  265. try {
  266. in.close();
  267. } catch (IOException e) {
  268. Log_OC.e(TAG, "Error closing input stream during copy", e);
  269. }
  270. }
  271. if (out != null) {
  272. try {
  273. out.close();
  274. } catch (IOException e) {
  275. Log_OC.e(TAG, "Error closing output stream during copy", e);
  276. }
  277. }
  278. }
  279. return ret;
  280. }
  281. public static boolean moveFile(File sourceFile, File targetFile) throws IOException {
  282. if (copyFile(sourceFile, targetFile)) {
  283. return sourceFile.delete();
  284. } else {
  285. return false;
  286. }
  287. }
  288. public static void deleteRecursively(File file, FileDataStorageManager storageManager) {
  289. if (file.isDirectory()) {
  290. for (File child : file.listFiles()) {
  291. deleteRecursively(child, storageManager);
  292. }
  293. }
  294. storageManager.deleteFileInMediaScan(file.getAbsolutePath());
  295. file.delete();
  296. }
  297. public static boolean checkIfFileFinishedSaving(OCFile file) {
  298. long lastModified = 0;
  299. long lastSize = 0;
  300. File realFile = new File(file.getStoragePath());
  301. if (realFile.lastModified() != file.getModificationTimestamp() && realFile.length() != file.getFileLength()) {
  302. while ((realFile.lastModified() != lastModified) && (realFile.length() != lastSize)) {
  303. lastModified = realFile.lastModified();
  304. lastSize = realFile.length();
  305. try {
  306. Thread.sleep(1000);
  307. } catch (InterruptedException e) {
  308. Log.d(TAG, "Failed to sleep for a bit");
  309. }
  310. }
  311. }
  312. return true;
  313. }
  314. /**
  315. * Checks and returns true if file itself or ancestor is encrypted
  316. *
  317. * @param file file to check
  318. * @param storageManager up to date reference to storage manager
  319. * @return true if file itself or ancestor is encrypted
  320. */
  321. public static boolean checkEncryptionStatus(OCFile file, FileDataStorageManager storageManager) {
  322. if (file.isEncrypted()) {
  323. return true;
  324. }
  325. while (!OCFile.ROOT_PATH.equals(file.getRemotePath())) {
  326. if (file.isEncrypted()) {
  327. return true;
  328. }
  329. file = storageManager.getFileById(file.getParentId());
  330. }
  331. return false;
  332. }
  333. }