FileStorageUtils.java 13 KB

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