FileStorageUtils.java 13 KB

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