Show share with users option if the server supports search users function
[pub/Android/ownCloud.git] / src / com / owncloud / android / utils / FileStorageUtils.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 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
21 package com.owncloud.android.utils;
22
23 import java.io.File;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.Vector;
27
28 import third_parties.daveKoeller.AlphanumComparator;
29
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.resources.files.RemoteFile;
34
35 import android.accounts.Account;
36 import android.annotation.SuppressLint;
37 import android.content.Context;
38 import android.content.SharedPreferences;
39 import android.preference.PreferenceManager;
40 import android.net.Uri;
41 import android.os.Environment;
42 import android.os.StatFs;
43 import android.webkit.MimeTypeMap;
44
45
46 /**
47 * Static methods to help in access to local file system.
48 */
49 public class FileStorageUtils {
50 public static final Integer SORT_NAME = 0;
51 public static final Integer SORT_DATE = 1;
52 public static final Integer SORT_SIZE = 2;
53 public static Integer mSortOrder = SORT_NAME;
54 public static Boolean mSortAscending = true;
55
56
57 public static final String getSavePath(String accountName) {
58 File sdCard = Environment.getExternalStorageDirectory();
59 return sdCard.getAbsolutePath() + "/" + MainApp.getDataFolder() + "/" + Uri.encode(accountName, "@");
60 // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
61 }
62
63 public static final String getDefaultSavePathFor(String accountName, OCFile file) {
64 return getSavePath(accountName) + file.getRemotePath();
65 }
66
67 public static final String getTemporalPath(String accountName) {
68 File sdCard = Environment.getExternalStorageDirectory();
69 return sdCard.getAbsolutePath() + "/" + MainApp.getDataFolder() + "/tmp/" + Uri.encode(accountName, "@");
70 // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B
71 }
72
73 @SuppressLint("NewApi")
74 public static final long getUsableSpace(String accountName) {
75 File savePath = Environment.getExternalStorageDirectory();
76 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
77 return savePath.getUsableSpace();
78
79 } else {
80 StatFs stats = new StatFs(savePath.getAbsolutePath());
81 return stats.getAvailableBlocks() * stats.getBlockSize();
82 }
83
84 }
85
86 public static final String getLogPath() {
87 return Environment.getExternalStorageDirectory() + File.separator + MainApp.getDataFolder() + File.separator + "log";
88 }
89
90 public static String getInstantUploadFilePath(Context context, String fileName) {
91 SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
92 String uploadPathdef = context.getString(R.string.instant_upload_path);
93 String uploadPath = pref.getString("instant_upload_path", uploadPathdef);
94 String value = uploadPath + OCFile.PATH_SEPARATOR + (fileName == null ? "" : fileName);
95 return value;
96 }
97
98 /**
99 * Gets the composed path when video is or must be stored
100 * @param context
101 * @param fileName: video file name
102 * @return String: video file path composed
103 */
104 public static String getInstantVideoUploadFilePath(Context context, String fileName) {
105 SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
106 String uploadVideoPathdef = context.getString(R.string.instant_upload_path);
107 String uploadVideoPath = pref.getString("instant_video_upload_path", uploadVideoPathdef);
108 String value = uploadVideoPath + OCFile.PATH_SEPARATOR + (fileName == null ? "" : fileName);
109 return value;
110 }
111
112 public static String getParentPath(String remotePath) {
113 String parentPath = new File(remotePath).getParent();
114 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
115 return parentPath;
116 }
117
118 /**
119 * Creates and populates a new {@link OCFile} object with the data read from the server.
120 *
121 * @param remote remote file read from the server (remote file or folder).
122 * @return New OCFile instance representing the remote resource described by remote.
123 */
124 public static OCFile fillOCFile(RemoteFile remote) {
125 OCFile file = new OCFile(remote.getRemotePath());
126 file.setCreationTimestamp(remote.getCreationTimestamp());
127 file.setFileLength(remote.getLength());
128 file.setMimetype(remote.getMimeType());
129 file.setModificationTimestamp(remote.getModifiedTimestamp());
130 file.setEtag(remote.getEtag());
131 file.setPermissions(remote.getPermissions());
132 file.setRemoteId(remote.getRemoteId());
133 return file;
134 }
135
136 /**
137 * Creates and populates a new {@link RemoteFile} object with the data read from an {@link OCFile}.
138 *
139 * @param ocFile OCFile
140 * @return New RemoteFile instance representing the resource described by ocFile.
141 */
142 public static RemoteFile fillRemoteFile(OCFile ocFile){
143 RemoteFile file = new RemoteFile(ocFile.getRemotePath());
144 file.setCreationTimestamp(ocFile.getCreationTimestamp());
145 file.setLength(ocFile.getFileLength());
146 file.setMimeType(ocFile.getMimetype());
147 file.setModifiedTimestamp(ocFile.getModificationTimestamp());
148 file.setEtag(ocFile.getEtag());
149 file.setPermissions(ocFile.getPermissions());
150 file.setRemoteId(ocFile.getRemoteId());
151 return file;
152 }
153
154 /**
155 * Sorts all filenames, regarding last user decision
156 */
157 public static Vector<OCFile> sortFolder(Vector<OCFile> files){
158 switch (mSortOrder){
159 case 0:
160 files = FileStorageUtils.sortByName(files);
161 break;
162 case 1:
163 files = FileStorageUtils.sortByDate(files);
164 break;
165 case 2:
166 // mFiles = FileStorageUtils.sortBySize(mSortAscending);
167 break;
168 }
169
170 return files;
171 }
172
173 /**
174 * Sorts list by Date
175 * @param files
176 */
177 public static Vector<OCFile> sortByDate(Vector<OCFile> files){
178 final Integer val;
179 if (mSortAscending){
180 val = 1;
181 } else {
182 val = -1;
183 }
184
185 Collections.sort(files, new Comparator<OCFile>() {
186 public int compare(OCFile o1, OCFile o2) {
187 if (o1.isFolder() && o2.isFolder()) {
188 Long obj1 = o1.getModificationTimestamp();
189 return val * obj1.compareTo(o2.getModificationTimestamp());
190 }
191 else if (o1.isFolder()) {
192 return -1;
193 } else if (o2.isFolder()) {
194 return 1;
195 } else if (o1.getModificationTimestamp() == 0 || o2.getModificationTimestamp() == 0){
196 return 0;
197 } else {
198 Long obj1 = o1.getModificationTimestamp();
199 return val * obj1.compareTo(o2.getModificationTimestamp());
200 }
201 }
202 });
203
204 return files;
205 }
206
207 // /**
208 // * Sorts list by Size
209 // * @param sortAscending true: ascending, false: descending
210 // */
211 // public static Vector<OCFile> sortBySize(Vector<OCFile> files){
212 // final Integer val;
213 // if (mSortAscending){
214 // val = 1;
215 // } else {
216 // val = -1;
217 // }
218 //
219 // Collections.sort(files, new Comparator<OCFile>() {
220 // public int compare(OCFile o1, OCFile o2) {
221 // if (o1.isFolder() && o2.isFolder()) {
222 // Long obj1 = getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o1)));
223 // return val * obj1.compareTo(getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o2))));
224 // }
225 // else if (o1.isFolder()) {
226 // return -1;
227 // } else if (o2.isFolder()) {
228 // return 1;
229 // } else if (o1.getFileLength() == 0 || o2.getFileLength() == 0){
230 // return 0;
231 // } else {
232 // Long obj1 = o1.getFileLength();
233 // return val * obj1.compareTo(o2.getFileLength());
234 // }
235 // }
236 // });
237 //
238 // return files;
239 // }
240
241 /**
242 * Sorts list by Name
243 * @param files files to sort
244 */
245 public static Vector<OCFile> sortByName(Vector<OCFile> files){
246 final Integer val;
247 if (mSortAscending){
248 val = 1;
249 } else {
250 val = -1;
251 }
252
253 Collections.sort(files, new Comparator<OCFile>() {
254 public int compare(OCFile o1, OCFile o2) {
255 if (o1.isFolder() && o2.isFolder()) {
256 return val * new AlphanumComparator().compare(o1, o2);
257 } else if (o1.isFolder()) {
258 return -1;
259 } else if (o2.isFolder()) {
260 return 1;
261 }
262 return val * new AlphanumComparator().compare(o1, o2);
263 }
264 });
265
266 return files;
267 }
268
269 /**
270 * Local Folder size
271 * @param dir File
272 * @return Size in bytes
273 */
274 public static long getFolderSize(File dir) {
275 if (dir.exists()) {
276 long result = 0;
277 File[] fileList = dir.listFiles();
278 for(int i = 0; i < fileList.length; i++) {
279 if(fileList[i].isDirectory()) {
280 result += getFolderSize(fileList[i]);
281 } else {
282 result += fileList[i].length();
283 }
284 }
285 return result;
286 }
287 return 0;
288 }
289
290 /**
291 * Mimetype String of a file
292 * @param path
293 * @return
294 */
295 public static String getMimeTypeFromName(String path) {
296 String extension = "";
297 int pos = path.lastIndexOf('.');
298 if (pos >= 0) {
299 extension = path.substring(pos + 1);
300 }
301 String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
302 return (result != null) ? result : "";
303 }
304
305 /**
306 * Scans the default location for saving local copies of files searching for
307 * a 'lost' file with the same full name as the {@link OCFile} received as
308 * parameter.
309 *
310 * This method helps to keep linked local copies of the files when the app is uninstalled, and then
311 * reinstalled in the device. OR after the cache of the app was deleted in system settings.
312 *
313 * The method is assuming that all the local changes in the file where synchronized in the past. This is dangerous,
314 * but assuming the contrary could lead to massive unnecessary synchronizations of downloaded file after deleting
315 * the app cache.
316 *
317 * This should be changed in the near future to avoid any chance of data loss, but we need to add some options
318 * to limit hard automatic synchronizations to wifi, unless the user wants otherwise.
319 *
320 * @param file File to associate a possible 'lost' local file.
321 * @param account Account holding file.
322 */
323 public static void searchForLocalFileInDefaultPath(OCFile file, Account account) {
324 if (file.getStoragePath() == null && !file.isFolder()) {
325 File f = new File(FileStorageUtils.getDefaultSavePathFor(account.name, file));
326 if (f.exists()) {
327 file.setStoragePath(f.getAbsolutePath());
328 file.setLastSyncDateForData(f.lastModified());
329 }
330 }
331 }
332
333 }