Merge pull request #7 from Mic92/master
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / FileDataStorageManager.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.datamodel;
20
21 import java.io.File;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Vector;
27
28 import com.owncloud.android.db.ProviderMeta;
29 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
30 import com.owncloud.android.utils.FileStorageUtils;
31
32 import android.accounts.Account;
33 import android.content.ContentProviderClient;
34 import android.content.ContentProviderOperation;
35 import android.content.ContentProviderResult;
36 import android.content.ContentResolver;
37 import android.content.ContentValues;
38 import android.content.OperationApplicationException;
39 import android.database.Cursor;
40 import android.net.Uri;
41 import android.os.RemoteException;
42 import android.util.Log;
43
44 public class FileDataStorageManager implements DataStorageManager {
45
46 private ContentResolver mContentResolver;
47 private ContentProviderClient mContentProvider;
48 private Account mAccount;
49
50 private static String TAG = "FileDataStorageManager";
51
52 public FileDataStorageManager(Account account, ContentResolver cr) {
53 mContentProvider = null;
54 mContentResolver = cr;
55 mAccount = account;
56 }
57
58 public FileDataStorageManager(Account account, ContentProviderClient cp) {
59 mContentProvider = cp;
60 mContentResolver = null;
61 mAccount = account;
62 }
63
64 @Override
65 public OCFile getFileByPath(String path) {
66 Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
67 OCFile file = null;
68 if (c.moveToFirst()) {
69 file = createFileInstance(c);
70 }
71 c.close();
72 return file;
73 }
74
75 @Override
76 public OCFile getFileById(long id) {
77 Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
78 OCFile file = null;
79 if (c.moveToFirst()) {
80 file = createFileInstance(c);
81 }
82 c.close();
83 return file;
84 }
85
86 public OCFile getFileByLocalPath(String path) {
87 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
88 OCFile file = null;
89 if (c.moveToFirst()) {
90 file = createFileInstance(c);
91 }
92 c.close();
93 return file;
94 }
95
96 @Override
97 public boolean fileExists(long id) {
98 return fileExists(ProviderTableMeta._ID, String.valueOf(id));
99 }
100
101 @Override
102 public boolean fileExists(String path) {
103 return fileExists(ProviderTableMeta.FILE_PATH, path);
104 }
105
106 @Override
107 public boolean saveFile(OCFile file) {
108 boolean overriden = false;
109 ContentValues cv = new ContentValues();
110 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
111 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
112 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
113 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
114 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
115 if (file.getParentId() != 0)
116 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
117 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
118 if (!file.isDirectory())
119 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
120 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
121 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
122 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
123 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
124
125 boolean sameRemotePath = fileExists(file.getRemotePath());
126 if (sameRemotePath ||
127 fileExists(file.getFileId()) ) { // for renamed files; no more delete and create
128
129 if (sameRemotePath) {
130 OCFile oldFile = getFileByPath(file.getRemotePath());
131 file.setFileId(oldFile.getFileId());
132 }
133
134 overriden = true;
135 if (getContentResolver() != null) {
136 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
137 ProviderTableMeta._ID + "=?",
138 new String[] { String.valueOf(file.getFileId()) });
139 } else {
140 try {
141 getContentProvider().update(ProviderTableMeta.CONTENT_URI,
142 cv, ProviderTableMeta._ID + "=?",
143 new String[] { String.valueOf(file.getFileId()) });
144 } catch (RemoteException e) {
145 Log.e(TAG,
146 "Fail to insert insert file to database "
147 + e.getMessage());
148 }
149 }
150 } else {
151 Uri result_uri = null;
152 if (getContentResolver() != null) {
153 result_uri = getContentResolver().insert(
154 ProviderTableMeta.CONTENT_URI_FILE, cv);
155 } else {
156 try {
157 result_uri = getContentProvider().insert(
158 ProviderTableMeta.CONTENT_URI_FILE, cv);
159 } catch (RemoteException e) {
160 Log.e(TAG,
161 "Fail to insert insert file to database "
162 + e.getMessage());
163 }
164 }
165 if (result_uri != null) {
166 long new_id = Long.parseLong(result_uri.getPathSegments()
167 .get(1));
168 file.setFileId(new_id);
169 }
170 }
171
172 if (file.isDirectory() && file.needsUpdatingWhileSaving())
173 for (OCFile f : getDirectoryContent(file))
174 saveFile(f);
175
176 return overriden;
177 }
178
179
180 @Override
181 public void saveFiles(List<OCFile> files) {
182
183 Iterator<OCFile> filesIt = files.iterator();
184 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(files.size());
185 OCFile file = null;
186
187 // prepare operations to perform
188 while (filesIt.hasNext()) {
189 file = filesIt.next();
190 ContentValues cv = new ContentValues();
191 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
192 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
193 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
194 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
195 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
196 if (file.getParentId() != 0)
197 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
198 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
199 if (!file.isDirectory())
200 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
201 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
202 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
203 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
204 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
205
206 if (fileExists(file.getRemotePath())) {
207 OCFile oldFile = getFileByPath(file.getRemotePath());
208 file.setFileId(oldFile.getFileId());
209 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
210 withValues(cv).
211 withSelection( ProviderTableMeta._ID + "=?",
212 new String[] { String.valueOf(file.getFileId()) })
213 .build());
214
215 } else if (fileExists(file.getFileId())) {
216 OCFile oldFile = getFileById(file.getFileId());
217 if (file.getStoragePath() == null && oldFile.getStoragePath() != null)
218 file.setStoragePath(oldFile.getStoragePath());
219 if (!file.isDirectory());
220 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
221
222 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
223 withValues(cv).
224 withSelection( ProviderTableMeta._ID + "=?",
225 new String[] { String.valueOf(file.getFileId()) })
226 .build());
227
228 } else {
229 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
230 }
231 }
232
233 // apply operations in batch
234 ContentProviderResult[] results = null;
235 try {
236 if (getContentResolver() != null) {
237 results = getContentResolver().applyBatch(ProviderMeta.AUTHORITY_FILES, operations);
238
239 } else {
240 results = getContentProvider().applyBatch(operations);
241 }
242
243 } catch (OperationApplicationException e) {
244 Log.e(TAG, "Fail to update/insert list of files to database " + e.getMessage());
245
246 } catch (RemoteException e) {
247 Log.e(TAG, "Fail to update/insert list of files to database " + e.getMessage());
248 }
249
250 // update new id in file objects for insertions
251 if (results != null) {
252 long newId;
253 for (int i=0; i<results.length; i++) {
254 if (results[i].uri != null) {
255 newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
256 files.get(i).setFileId(newId);
257 //Log.v(TAG, "Found and added id in insertion for " + files.get(i).getRemotePath());
258 }
259 }
260 }
261
262 for (OCFile aFile : files) {
263 if (aFile.isDirectory() && aFile.needsUpdatingWhileSaving())
264 saveFiles(getDirectoryContent(aFile));
265 }
266
267 }
268
269 public void setAccount(Account account) {
270 mAccount = account;
271 }
272
273 public Account getAccount() {
274 return mAccount;
275 }
276
277 public void setContentResolver(ContentResolver cr) {
278 mContentResolver = cr;
279 }
280
281 public ContentResolver getContentResolver() {
282 return mContentResolver;
283 }
284
285 public void setContentProvider(ContentProviderClient cp) {
286 mContentProvider = cp;
287 }
288
289 public ContentProviderClient getContentProvider() {
290 return mContentProvider;
291 }
292
293 @Override
294 public Vector<OCFile> getDirectoryContent(OCFile f) {
295 if (f != null && f.isDirectory() && f.getFileId() != -1) {
296 Vector<OCFile> ret = new Vector<OCFile>();
297
298 Uri req_uri = Uri.withAppendedPath(
299 ProviderTableMeta.CONTENT_URI_DIR,
300 String.valueOf(f.getFileId()));
301 Cursor c = null;
302
303 if (getContentProvider() != null) {
304 try {
305 c = getContentProvider().query(req_uri, null,
306 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
307 new String[] { mAccount.name }, null);
308 } catch (RemoteException e) {
309 Log.e(TAG, e.getMessage());
310 return ret;
311 }
312 } else {
313 c = getContentResolver().query(req_uri, null,
314 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
315 new String[] { mAccount.name }, null);
316 }
317
318 if (c.moveToFirst()) {
319 do {
320 OCFile child = createFileInstance(c);
321 ret.add(child);
322 } while (c.moveToNext());
323 }
324
325 c.close();
326
327 Collections.sort(ret);
328
329 return ret;
330 }
331 return null;
332 }
333
334 private boolean fileExists(String cmp_key, String value) {
335 Cursor c;
336 if (getContentResolver() != null) {
337 c = getContentResolver()
338 .query(ProviderTableMeta.CONTENT_URI,
339 null,
340 cmp_key + "=? AND "
341 + ProviderTableMeta.FILE_ACCOUNT_OWNER
342 + "=?",
343 new String[] { value, mAccount.name }, null);
344 } else {
345 try {
346 c = getContentProvider().query(
347 ProviderTableMeta.CONTENT_URI,
348 null,
349 cmp_key + "=? AND "
350 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
351 new String[] { value, mAccount.name }, null);
352 } catch (RemoteException e) {
353 Log.e(TAG,
354 "Couldn't determine file existance, assuming non existance: "
355 + e.getMessage());
356 return false;
357 }
358 }
359 boolean retval = c.moveToFirst();
360 c.close();
361 return retval;
362 }
363
364 private Cursor getCursorForValue(String key, String value) {
365 Cursor c = null;
366 if (getContentResolver() != null) {
367 c = getContentResolver()
368 .query(ProviderTableMeta.CONTENT_URI,
369 null,
370 key + "=? AND "
371 + ProviderTableMeta.FILE_ACCOUNT_OWNER
372 + "=?",
373 new String[] { value, mAccount.name }, null);
374 } else {
375 try {
376 c = getContentProvider().query(
377 ProviderTableMeta.CONTENT_URI,
378 null,
379 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
380 + "=?", new String[] { value, mAccount.name },
381 null);
382 } catch (RemoteException e) {
383 Log.e(TAG, "Could not get file details: " + e.getMessage());
384 c = null;
385 }
386 }
387 return c;
388 }
389
390 private OCFile createFileInstance(Cursor c) {
391 OCFile file = null;
392 if (c != null) {
393 file = new OCFile(c.getString(c
394 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
395 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
396 file.setParentId(c.getLong(c
397 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
398 file.setMimetype(c.getString(c
399 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
400 if (!file.isDirectory()) {
401 file.setStoragePath(c.getString(c
402 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
403 if (file.getStoragePath() == null) {
404 // try to find existing file and bind it with current account; - with the current update of SynchronizeFolderOperation, this won't be necessary anymore after a full synchronization of the account
405 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
406 if (f.exists()) {
407 file.setStoragePath(f.getAbsolutePath());
408 file.setLastSyncDateForData(f.lastModified());
409 }
410 }
411 }
412 file.setFileLength(c.getLong(c
413 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
414 file.setCreationTimestamp(c.getLong(c
415 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
416 file.setModificationTimestamp(c.getLong(c
417 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
418 file.setLastSyncDateForProperties(c.getLong(c
419 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
420 file.setLastSyncDateForData(c.getLong(c.
421 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
422 file.setKeepInSync(c.getInt(
423 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
424 }
425 return file;
426 }
427
428 @Override
429 public void removeFile(OCFile file, boolean removeLocalCopy) {
430 Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
431 if (getContentProvider() != null) {
432 try {
433 getContentProvider().delete(file_uri,
434 ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
435 new String[]{mAccount.name});
436 } catch (RemoteException e) {
437 e.printStackTrace();
438 }
439 } else {
440 getContentResolver().delete(file_uri,
441 ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
442 new String[]{mAccount.name});
443 }
444 if (file.isDown() && removeLocalCopy) {
445 new File(file.getStoragePath()).delete();
446 }
447 if (file.isDirectory() && removeLocalCopy) {
448 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
449 if (f.exists() && f.isDirectory() && (f.list() == null || f.list().length == 0)) {
450 f.delete();
451 }
452 }
453 }
454
455 @Override
456 public void removeDirectory(OCFile dir, boolean removeDBData, boolean removeLocalContent) {
457 // TODO consider possible failures
458 if (dir != null && dir.isDirectory() && dir.getFileId() != -1) {
459 Vector<OCFile> children = getDirectoryContent(dir);
460 if (children != null) {
461 OCFile child = null;
462 for (int i=0; i<children.size(); i++) {
463 child = children.get(i);
464 if (child.isDirectory()) {
465 removeDirectory(child, removeDBData, removeLocalContent);
466 } else {
467 if (removeDBData) {
468 removeFile(child, removeLocalContent);
469 } else if (removeLocalContent) {
470 if (child.isDown()) {
471 new File(child.getStoragePath()).delete();
472 }
473 }
474 }
475 }
476 if (removeDBData) {
477 removeFile(dir, true);
478 }
479 }
480 }
481 }
482
483
484 /**
485 * Updates database for a folder that was moved to a different location.
486 *
487 * TODO explore better (faster) implementations
488 * TODO throw exceptions up !
489 */
490 @Override
491 public void moveDirectory(OCFile dir, String newPath) {
492 // TODO check newPath
493
494 if (dir != null && dir.isDirectory() && dir.fileExists() && !dir.getFileName().equals(OCFile.PATH_SEPARATOR)) {
495 /// 1. get all the descendants of 'dir' in a single QUERY (including 'dir')
496 Cursor c = null;
497 if (getContentProvider() != null) {
498 try {
499 c = getContentProvider().query(ProviderTableMeta.CONTENT_URI,
500 null,
501 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ?",
502 new String[] { mAccount.name, dir.getRemotePath() + "%" }, null);
503 } catch (RemoteException e) {
504 Log.e(TAG, e.getMessage());
505 }
506 } else {
507 c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
508 null,
509 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ?",
510 new String[] { mAccount.name, dir.getRemotePath() + "%" }, null);
511 }
512
513 /// 2. prepare a batch of update operations to change all the descendants
514 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(c.getCount());
515 int lengthOfOldPath = dir.getRemotePath().length();
516 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
517 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
518 if (c.moveToFirst()) {
519 do {
520 ContentValues cv = new ContentValues(); // don't take the constructor out of the loop and clear the object
521 OCFile child = createFileInstance(c);
522 cv.put(ProviderTableMeta.FILE_PATH, newPath + child.getRemotePath().substring(lengthOfOldPath));
523 if (child.getStoragePath() != null && child.getStoragePath().startsWith(defaultSavePath)) {
524 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, defaultSavePath + newPath + child.getStoragePath().substring(lengthOfOldStoragePath));
525 }
526 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
527 withValues(cv).
528 withSelection( ProviderTableMeta._ID + "=?",
529 new String[] { String.valueOf(child.getFileId()) })
530 .build());
531 } while (c.moveToNext());
532 }
533 c.close();
534
535 /// 3. apply updates in batch
536 try {
537 if (getContentResolver() != null) {
538 getContentResolver().applyBatch(ProviderMeta.AUTHORITY_FILES, operations);
539
540 } else {
541 getContentProvider().applyBatch(operations);
542 }
543
544 } catch (OperationApplicationException e) {
545 Log.e(TAG, "Fail to update descendants of " + dir.getFileId() + " in database", e);
546
547 } catch (RemoteException e) {
548 Log.e(TAG, "Fail to update desendants of " + dir.getFileId() + " in database", e);
549 }
550
551 }
552 }
553
554 }