FileStorageUtils.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. */
  20. package com.owncloud.android.utils;
  21. import android.accounts.Account;
  22. import android.annotation.SuppressLint;
  23. import android.content.Context;
  24. import android.content.SharedPreferences;
  25. import android.net.Uri;
  26. import android.os.Environment;
  27. import android.os.StatFs;
  28. import android.preference.PreferenceManager;
  29. import android.webkit.MimeTypeMap;
  30. import com.owncloud.android.MainApp;
  31. import com.owncloud.android.R;
  32. import com.owncloud.android.datamodel.OCFile;
  33. import com.owncloud.android.lib.common.utils.Log_OC;
  34. import com.owncloud.android.lib.resources.files.RemoteFile;
  35. import java.io.File;
  36. import java.text.SimpleDateFormat;
  37. import java.util.ArrayList;
  38. import java.util.Arrays;
  39. import java.util.Collections;
  40. import java.util.Comparator;
  41. import java.util.Date;
  42. import java.util.List;
  43. import java.util.Locale;
  44. import java.util.Vector;
  45. import third_parties.daveKoeller.AlphanumComparator;
  46. /**
  47. * Static methods to help in access to local file system.
  48. */
  49. public class FileStorageUtils {
  50. private static final String TAG = FileStorageUtils.class.getSimpleName();
  51. public static final Integer SORT_NAME = 0;
  52. public static final Integer SORT_DATE = 1;
  53. public static final Integer SORT_SIZE = 2;
  54. public static Integer mSortOrder = SORT_NAME;
  55. public static Boolean mSortAscending = true;
  56. /**
  57. * Takes a full path to owncloud file and removes beginning which is path to ownload data folder.
  58. * If fullPath does not start with that folder, fullPath is returned as is.
  59. */
  60. public static final String removeDataFolderPath(String fullPath) {
  61. File sdCard = Environment.getExternalStorageDirectory();
  62. String dataFolderPath = sdCard.getAbsolutePath() + "/" + MainApp.getDataFolder() + "/";
  63. if(fullPath.indexOf(dataFolderPath) == 0) {
  64. return fullPath.substring(dataFolderPath.length());
  65. }
  66. return fullPath;
  67. }
  68. /**
  69. * Get local owncloud storage path for accountName.
  70. */
  71. public static final String getSavePath(String accountName) {
  72. File sdCard = Environment.getExternalStorageDirectory();
  73. return sdCard.getAbsolutePath() + "/" + MainApp.getDataFolder() + "/" + Uri.encode(accountName, "@");
  74. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  75. // that can be in the accountName since 0.1.190B
  76. }
  77. /**
  78. * Get local path where OCFile file is to be stored after upload. That is,
  79. * corresponding local path (in local owncloud storage) to remote uploaded
  80. * file.
  81. */
  82. public static final String getDefaultSavePathFor(String accountName, OCFile file) {
  83. return getSavePath(accountName) + file.getRemotePath();
  84. }
  85. /**
  86. * Get absolute path to tmp folder inside datafolder in sd-card for given accountName.
  87. */
  88. public static final String getTemporalPath(String accountName) {
  89. File sdCard = Environment.getExternalStorageDirectory();
  90. return sdCard.getAbsolutePath() + "/" + MainApp.getDataFolder() + "/tmp/" + Uri.encode(accountName, "@");
  91. // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names,
  92. // that can be in the accountName since 0.1.190B
  93. }
  94. /**
  95. * Optimistic number of bytes available on sd-card. accountName is ignored.
  96. * @param accountName not used. can thus be null.
  97. * @return Optimistic number of available bytes (can be less)
  98. */
  99. @SuppressLint("NewApi")
  100. public static final long getUsableSpace(String accountName) {
  101. File savePath = Environment.getExternalStorageDirectory();
  102. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
  103. return savePath.getUsableSpace();
  104. } else {
  105. StatFs stats = new StatFs(savePath.getAbsolutePath());
  106. return stats.getAvailableBlocks() * stats.getBlockSize();
  107. }
  108. }
  109. public static final String getLogPath() {
  110. return Environment.getExternalStorageDirectory() + File.separator + MainApp.getDataFolder() + File.separator + "log";
  111. }
  112. /**
  113. * Returns the a string like 2016/08/ for the passed date. If date is 0 an empty
  114. * string is returned
  115. *
  116. * @param date: date in microseconds since 1st January 1970
  117. * @return
  118. */
  119. private static String getSubpathFromDate(long date) {
  120. if (date == 0) {
  121. return "";
  122. }
  123. try {
  124. SimpleDateFormat formatter = new SimpleDateFormat(
  125. "yyyy" + OCFile.PATH_SEPARATOR + "MM" + OCFile.PATH_SEPARATOR, Locale.ENGLISH);
  126. return formatter.format(new Date(date));
  127. }
  128. catch(RuntimeException ex) {
  129. Log_OC.w(TAG, "could not extract date from timestamp");
  130. return "";
  131. }
  132. }
  133. /**
  134. * Returns the InstantUploadFilePath on the owncloud instance
  135. *
  136. * @param context
  137. * @param fileName
  138. * @param dateTaken: Time in milliseconds since 1970 when the picture was taken.
  139. * @return
  140. */
  141. public static String getInstantUploadFilePath(Context context, String fileName, long dateTaken) {
  142. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
  143. String uploadPathdef = context.getString(R.string.instant_upload_path);
  144. String uploadPath = pref.getString("instant_upload_path", uploadPathdef);
  145. String subPath = "";
  146. if (com.owncloud.android.db.PreferenceManager.instantPictureUploadPathUseSubfolders(context)) {
  147. subPath = getSubpathFromDate(dateTaken);
  148. }
  149. return uploadPath + OCFile.PATH_SEPARATOR + subPath
  150. + (fileName == null ? "" : fileName);
  151. }
  152. /**
  153. * Gets the composed path when video is or must be stored
  154. * @param context
  155. * @param fileName: video file name
  156. * @return String: video file path composed
  157. */
  158. public static String getInstantVideoUploadFilePath(Context context, String fileName, long dateTaken) {
  159. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
  160. String uploadVideoPathdef = context.getString(R.string.instant_upload_path);
  161. String uploadVideoPath = pref.getString("instant_video_upload_path", uploadVideoPathdef);
  162. String subPath = "";
  163. if (com.owncloud.android.db.PreferenceManager.instantVideoUploadPathUseSubfolders(context)) {
  164. subPath = getSubpathFromDate(dateTaken);
  165. }
  166. return uploadVideoPath + OCFile.PATH_SEPARATOR + subPath
  167. + (fileName == null ? "" : fileName);
  168. }
  169. public static String getParentPath(String remotePath) {
  170. String parentPath = new File(remotePath).getParent();
  171. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  172. return parentPath;
  173. }
  174. /**
  175. * Creates and populates a new {@link OCFile} object with the data read from the server.
  176. *
  177. * @param remote remote file read from the server (remote file or folder).
  178. * @return New OCFile instance representing the remote resource described by remote.
  179. */
  180. public static OCFile fillOCFile(RemoteFile remote) {
  181. OCFile file = new OCFile(remote.getRemotePath());
  182. file.setCreationTimestamp(remote.getCreationTimestamp());
  183. if (remote.getMimeType().equalsIgnoreCase(MimeType.DIRECTORY)){
  184. file.setFileLength(remote.getSize());
  185. } else {
  186. file.setFileLength(remote.getLength());
  187. }
  188. file.setMimetype(remote.getMimeType());
  189. file.setModificationTimestamp(remote.getModifiedTimestamp());
  190. file.setEtag(remote.getEtag());
  191. file.setPermissions(remote.getPermissions());
  192. file.setRemoteId(remote.getRemoteId());
  193. return file;
  194. }
  195. /**
  196. * Creates and populates a new {@link RemoteFile} object with the data read from an {@link OCFile}.
  197. *
  198. * @param ocFile OCFile
  199. * @return New RemoteFile instance representing the resource described by ocFile.
  200. */
  201. public static RemoteFile fillRemoteFile(OCFile ocFile){
  202. RemoteFile file = new RemoteFile(ocFile.getRemotePath());
  203. file.setCreationTimestamp(ocFile.getCreationTimestamp());
  204. file.setLength(ocFile.getFileLength());
  205. file.setMimeType(ocFile.getMimetype());
  206. file.setModifiedTimestamp(ocFile.getModificationTimestamp());
  207. file.setEtag(ocFile.getEtag());
  208. file.setPermissions(ocFile.getPermissions());
  209. file.setRemoteId(ocFile.getRemoteId());
  210. return file;
  211. }
  212. /**
  213. * Sorts all filenames, regarding last user decision
  214. */
  215. public static Vector<OCFile> sortOcFolder(Vector<OCFile> files){
  216. switch (mSortOrder){
  217. case 0:
  218. files = FileStorageUtils.sortOCFilesByName(files);
  219. break;
  220. case 1:
  221. files = FileStorageUtils.sortOCFilesByDate(files);
  222. break;
  223. case 2:
  224. files = FileStorageUtils.sortOCFilesBySize(files);
  225. break;
  226. }
  227. files = FileStorageUtils.sortOCFilesByFavourite(files);
  228. return files;
  229. }
  230. /**
  231. * Sorts all filenames, regarding last user decision
  232. */
  233. public static File[] sortLocalFolder(File[] files){
  234. switch (mSortOrder){
  235. case 0:
  236. files = FileStorageUtils.sortLocalFilesByName(files);
  237. break;
  238. case 1:
  239. files = FileStorageUtils.sortLocalFilesByDate(files);
  240. break;
  241. case 2:
  242. files = FileStorageUtils.sortLocalFilesBySize(files);
  243. break;
  244. }
  245. return files;
  246. }
  247. /**
  248. * Sorts list by Date
  249. * @param files
  250. */
  251. public static Vector<OCFile> sortOCFilesByDate(Vector<OCFile> files){
  252. final int multiplier = mSortAscending ? 1 : -1;
  253. Collections.sort(files, new Comparator<OCFile>() {
  254. public int compare(OCFile o1, OCFile o2) {
  255. Long obj1 = o1.getModificationTimestamp();
  256. return multiplier * obj1.compareTo(o2.getModificationTimestamp());
  257. }
  258. });
  259. return files;
  260. }
  261. /**
  262. * Sorts list by Date
  263. * @param filesArray
  264. */
  265. public static File[] sortLocalFilesByDate(File[] filesArray){
  266. final int multiplier = mSortAscending ? 1 : -1;
  267. List<File> files = new ArrayList<File>(Arrays.asList(filesArray));
  268. Collections.sort(files, new Comparator<File>() {
  269. public int compare(File o1, File o2) {
  270. Long obj1 = o1.lastModified();
  271. return multiplier * obj1.compareTo(o2.lastModified());
  272. }
  273. });
  274. File[] returnArray = new File[files.size()];
  275. return files.toArray(returnArray);
  276. }
  277. /**
  278. * Sorts list by Size
  279. */
  280. public static Vector<OCFile> sortOCFilesBySize(Vector<OCFile> files){
  281. final int multiplier = mSortAscending ? 1 : -1;
  282. Collections.sort(files, new Comparator<OCFile>() {
  283. public int compare(OCFile o1, OCFile o2) {
  284. if (o1.isFolder() && o2.isFolder()) {
  285. Long obj1 = o1.getFileLength();
  286. return multiplier * obj1.compareTo(o2.getFileLength());
  287. } else if (o1.isFolder()) {
  288. return -1;
  289. } else if (o2.isFolder()) {
  290. return 1;
  291. } else {
  292. Long obj1 = o1.getFileLength();
  293. return multiplier * obj1.compareTo(o2.getFileLength());
  294. }
  295. }
  296. });
  297. return files;
  298. }
  299. /**
  300. * Sorts list by Size
  301. */
  302. public static File[] sortLocalFilesBySize(File[] filesArray) {
  303. final int multiplier = mSortAscending ? 1 : -1;
  304. List<File> files = new ArrayList<File>(Arrays.asList(filesArray));
  305. Collections.sort(files, new Comparator<File>() {
  306. public int compare(File o1, File o2) {
  307. if (o1.isDirectory() && o2.isDirectory()) {
  308. Long obj1 = getFolderSize(o1);
  309. return multiplier * obj1.compareTo(getFolderSize(o2));
  310. } else if (o1.isDirectory()) {
  311. return -1;
  312. } else if (o2.isDirectory()) {
  313. return 1;
  314. } else {
  315. Long obj1 = o1.length();
  316. return multiplier * obj1.compareTo(o2.length());
  317. }
  318. }
  319. });
  320. File[] returnArray = new File[files.size()];
  321. return files.toArray(returnArray);
  322. }
  323. /**
  324. * Sorts list by Name
  325. * @param files files to sort
  326. */
  327. public static Vector<OCFile> sortOCFilesByName(Vector<OCFile> files){
  328. final int multiplier = mSortAscending ? 1 : -1;
  329. Collections.sort(files, new Comparator<OCFile>() {
  330. public int compare(OCFile o1, OCFile o2) {
  331. if (o1.isFolder() && o2.isFolder()) {
  332. return multiplier * new AlphanumComparator().compare(o1, o2);
  333. } else if (o1.isFolder()) {
  334. return -1;
  335. } else if (o2.isFolder()) {
  336. return 1;
  337. }
  338. return multiplier * new AlphanumComparator().compare(o1, o2);
  339. }
  340. });
  341. return files;
  342. }
  343. /**
  344. * Sorts list by Name
  345. * @param filesArray files to sort
  346. */
  347. public static File[] sortLocalFilesByName(File[] filesArray) {
  348. final int multiplier = mSortAscending ? 1 : -1;
  349. List<File> files = new ArrayList<File>(Arrays.asList(filesArray));
  350. Collections.sort(files, new Comparator<File>() {
  351. public int compare(File o1, File o2) {
  352. if (o1.isDirectory() && o2.isDirectory()) {
  353. return multiplier * o1.getPath().toLowerCase().compareTo(o2.getPath().toLowerCase());
  354. } else if (o1.isDirectory()) {
  355. return -1;
  356. } else if (o2.isDirectory()) {
  357. return 1;
  358. }
  359. return multiplier * new AlphanumComparator().compare(o1.getPath().toLowerCase(),
  360. o2.getPath().toLowerCase());
  361. }
  362. });
  363. File[] returnArray = new File[files.size()];
  364. return files.toArray(returnArray);
  365. }
  366. /**
  367. * Sorts list by Favourites
  368. * @param files files to sort
  369. */
  370. public static Vector<OCFile> sortOCFilesByFavourite(Vector<OCFile> files){
  371. Collections.sort(files, new Comparator<OCFile>() {
  372. public int compare(OCFile o1, OCFile o2) {
  373. if (o1.isFavorite() && o2.isFavorite()) {
  374. return 0;
  375. } else if (o1.isFavorite()) {
  376. return -1;
  377. } else if (o2.isFavorite()) {
  378. return 1;
  379. }
  380. return 0;
  381. }
  382. });
  383. return files;
  384. }
  385. /**
  386. * Local Folder size
  387. * @param dir File
  388. * @return Size in bytes
  389. */
  390. public static long getFolderSize(File dir) {
  391. if (dir.exists()) {
  392. long result = 0;
  393. File[] fileList = dir.listFiles();
  394. for(int i = 0; i < fileList.length; i++) {
  395. if(fileList[i].isDirectory()) {
  396. result += getFolderSize(fileList[i]);
  397. } else {
  398. result += fileList[i].length();
  399. }
  400. }
  401. return result;
  402. }
  403. return 0;
  404. }
  405. /**
  406. * Mimetype String of a file
  407. * @param path
  408. * @return
  409. */
  410. public static String getMimeTypeFromName(String path) {
  411. String extension = "";
  412. int pos = path.lastIndexOf('.');
  413. if (pos >= 0) {
  414. extension = path.substring(pos + 1);
  415. }
  416. String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
  417. return (result != null) ? result : "";
  418. }
  419. /**
  420. * Scans the default location for saving local copies of files searching for
  421. * a 'lost' file with the same full name as the {@link OCFile} received as
  422. * parameter.
  423. *
  424. * This method helps to keep linked local copies of the files when the app is uninstalled, and then
  425. * reinstalled in the device. OR after the cache of the app was deleted in system settings.
  426. *
  427. * The method is assuming that all the local changes in the file where synchronized in the past. This is dangerous,
  428. * but assuming the contrary could lead to massive unnecessary synchronizations of downloaded file after deleting
  429. * the app cache.
  430. *
  431. * This should be changed in the near future to avoid any chance of data loss, but we need to add some options
  432. * to limit hard automatic synchronizations to wifi, unless the user wants otherwise.
  433. *
  434. * @param file File to associate a possible 'lost' local file.
  435. * @param account Account holding file.
  436. */
  437. public static void searchForLocalFileInDefaultPath(OCFile file, Account account) {
  438. if (file.getStoragePath() == null && !file.isFolder()) {
  439. File f = new File(FileStorageUtils.getDefaultSavePathFor(account.name, file));
  440. if (f.exists()) {
  441. file.setStoragePath(f.getAbsolutePath());
  442. file.setLastSyncDateForData(f.lastModified());
  443. }
  444. }
  445. }
  446. }