1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
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.
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.
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/>.
19 package com
.owncloud
.android
.datamodel
;
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
;
28 import com
.owncloud
.android
.db
.ProviderMeta
;
29 import com
.owncloud
.android
.db
.ProviderMeta
.ProviderTableMeta
;
30 import com
.owncloud
.android
.utils
.FileStorageUtils
;
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
;
44 public class FileDataStorageManager
implements DataStorageManager
{
46 private ContentResolver mContentResolver
;
47 private ContentProviderClient mContentProvider
;
48 private Account mAccount
;
50 private static String TAG
= "FileDataStorageManager";
52 public FileDataStorageManager(Account account
, ContentResolver cr
) {
53 mContentProvider
= null
;
54 mContentResolver
= cr
;
58 public FileDataStorageManager(Account account
, ContentProviderClient cp
) {
59 mContentProvider
= cp
;
60 mContentResolver
= null
;
65 public OCFile
getFileByPath(String path
) {
66 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_PATH
, path
);
68 if (c
.moveToFirst()) {
69 file
= createFileInstance(c
);
76 public OCFile
getFileById(long id
) {
77 Cursor c
= getCursorForValue(ProviderTableMeta
._ID
, String
.valueOf(id
));
79 if (c
.moveToFirst()) {
80 file
= createFileInstance(c
);
86 public OCFile
getFileByLocalPath(String path
) {
87 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_STORAGE_PATH
, path
);
89 if (c
.moveToFirst()) {
90 file
= createFileInstance(c
);
97 public boolean fileExists(long id
) {
98 return fileExists(ProviderTableMeta
._ID
, String
.valueOf(id
));
102 public boolean fileExists(String path
) {
103 return fileExists(ProviderTableMeta
.FILE_PATH
, path
);
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);
125 boolean sameRemotePath
= fileExists(file
.getRemotePath());
126 if (sameRemotePath
||
127 fileExists(file
.getFileId()) ) { // for renamed files; no more delete and create
129 if (sameRemotePath
) {
130 OCFile oldFile
= getFileByPath(file
.getRemotePath());
131 file
.setFileId(oldFile
.getFileId());
135 if (getContentResolver() != null
) {
136 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
,
137 ProviderTableMeta
._ID
+ "=?",
138 new String
[] { String
.valueOf(file
.getFileId()) });
141 getContentProvider().update(ProviderTableMeta
.CONTENT_URI
,
142 cv
, ProviderTableMeta
._ID
+ "=?",
143 new String
[] { String
.valueOf(file
.getFileId()) });
144 } catch (RemoteException e
) {
146 "Fail to insert insert file to database "
151 Uri result_uri
= null
;
152 if (getContentResolver() != null
) {
153 result_uri
= getContentResolver().insert(
154 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
157 result_uri
= getContentProvider().insert(
158 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
159 } catch (RemoteException e
) {
161 "Fail to insert insert file to database "
165 if (result_uri
!= null
) {
166 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
168 file
.setFileId(new_id
);
172 if (file
.isDirectory() && file
.needsUpdatingWhileSaving())
173 for (OCFile f
: getDirectoryContent(file
))
181 public void saveFiles(List
<OCFile
> files
) {
183 Iterator
<OCFile
> filesIt
= files
.iterator();
184 ArrayList
<ContentProviderOperation
> operations
= new ArrayList
<ContentProviderOperation
>(files
.size());
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);
206 if (fileExists(file
.getRemotePath())) {
207 OCFile oldFile
= getFileByPath(file
.getRemotePath());
208 file
.setFileId(oldFile
.getFileId());
209 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
211 withSelection( ProviderTableMeta
._ID
+ "=?",
212 new String
[] { String
.valueOf(file
.getFileId()) })
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());
222 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
224 withSelection( ProviderTableMeta
._ID
+ "=?",
225 new String
[] { String
.valueOf(file
.getFileId()) })
229 operations
.add(ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).withValues(cv
).build());
233 // apply operations in batch
234 ContentProviderResult
[] results
= null
;
236 if (getContentResolver() != null
) {
237 results
= getContentResolver().applyBatch(ProviderMeta
.AUTHORITY_FILES
, operations
);
240 results
= getContentProvider().applyBatch(operations
);
243 } catch (OperationApplicationException e
) {
244 Log
.e(TAG
, "Fail to update/insert list of files to database " + e
.getMessage());
246 } catch (RemoteException e
) {
247 Log
.e(TAG
, "Fail to update/insert list of files to database " + e
.getMessage());
250 // update new id in file objects for insertions
251 if (results
!= null
) {
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());
262 for (OCFile aFile
: files
) {
263 if (aFile
.isDirectory() && aFile
.needsUpdatingWhileSaving())
264 saveFiles(getDirectoryContent(aFile
));
269 public void setAccount(Account account
) {
273 public Account
getAccount() {
277 public void setContentResolver(ContentResolver cr
) {
278 mContentResolver
= cr
;
281 public ContentResolver
getContentResolver() {
282 return mContentResolver
;
285 public void setContentProvider(ContentProviderClient cp
) {
286 mContentProvider
= cp
;
289 public ContentProviderClient
getContentProvider() {
290 return mContentProvider
;
294 public Vector
<OCFile
> getDirectoryContent(OCFile f
) {
295 if (f
!= null
&& f
.isDirectory() && f
.getFileId() != -1) {
296 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
298 Uri req_uri
= Uri
.withAppendedPath(
299 ProviderTableMeta
.CONTENT_URI_DIR
,
300 String
.valueOf(f
.getFileId()));
303 if (getContentProvider() != null
) {
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());
313 c
= getContentResolver().query(req_uri
, null
,
314 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
315 new String
[] { mAccount
.name
}, null
);
318 if (c
.moveToFirst()) {
320 OCFile child
= createFileInstance(c
);
322 } while (c
.moveToNext());
327 Collections
.sort(ret
);
334 private boolean fileExists(String cmp_key
, String value
) {
336 if (getContentResolver() != null
) {
337 c
= getContentResolver()
338 .query(ProviderTableMeta
.CONTENT_URI
,
341 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
343 new String
[] { value
, mAccount
.name
}, null
);
346 c
= getContentProvider().query(
347 ProviderTableMeta
.CONTENT_URI
,
350 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
351 new String
[] { value
, mAccount
.name
}, null
);
352 } catch (RemoteException e
) {
354 "Couldn't determine file existance, assuming non existance: "
359 boolean retval
= c
.moveToFirst();
364 private Cursor
getCursorForValue(String key
, String value
) {
366 if (getContentResolver() != null
) {
367 c
= getContentResolver()
368 .query(ProviderTableMeta
.CONTENT_URI
,
371 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
373 new String
[] { value
, mAccount
.name
}, null
);
376 c
= getContentProvider().query(
377 ProviderTableMeta
.CONTENT_URI
,
379 key
+ "=? AND " + ProviderTableMeta
.FILE_ACCOUNT_OWNER
380 + "=?", new String
[] { value
, mAccount
.name
},
382 } catch (RemoteException e
) {
383 Log
.e(TAG
, "Could not get file details: " + e
.getMessage());
390 private OCFile
createFileInstance(Cursor c
) {
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
));
407 file
.setStoragePath(f
.getAbsolutePath());
408 file
.setLastSyncDateForData(f
.lastModified());
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
);
429 public void removeFile(OCFile file
, boolean removeLocalCopy
) {
430 Uri file_uri
= Uri
.withAppendedPath(ProviderTableMeta
.CONTENT_URI_FILE
, ""+file
.getFileId());
431 if (getContentProvider() != null
) {
433 getContentProvider().delete(file_uri
,
434 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+"=?",
435 new String
[]{mAccount
.name
});
436 } catch (RemoteException e
) {
440 getContentResolver().delete(file_uri
,
441 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+"=?",
442 new String
[]{mAccount
.name
});
444 if (file
.isDown() && removeLocalCopy
) {
445 new File(file
.getStoragePath()).delete();
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)) {
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
) {
462 for (int i
=0; i
<children
.size(); i
++) {
463 child
= children
.get(i
);
464 if (child
.isDirectory()) {
465 removeDirectory(child
, removeDBData
, removeLocalContent
);
468 removeFile(child
, removeLocalContent
);
469 } else if (removeLocalContent
) {
470 if (child
.isDown()) {
471 new File(child
.getStoragePath()).delete();
477 removeFile(dir
, true
);
485 * Updates database for a folder that was moved to a different location.
487 * TODO explore better (faster) implementations
488 * TODO throw exceptions up !
491 public void moveDirectory(OCFile dir
, String newPath
) {
492 // TODO check newPath
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')
497 if (getContentProvider() != null
) {
499 c
= getContentProvider().query(ProviderTableMeta
.CONTENT_URI
,
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());
507 c
= getContentResolver().query(ProviderTableMeta
.CONTENT_URI
,
509 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " + ProviderTableMeta
.FILE_PATH
+ " LIKE ?",
510 new String
[] { mAccount
.name
, dir
.getRemotePath() + "%" }, null
);
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()) {
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
));
526 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
528 withSelection( ProviderTableMeta
._ID
+ "=?",
529 new String
[] { String
.valueOf(child
.getFileId()) })
531 } while (c
.moveToNext());
535 /// 3. apply updates in batch
537 if (getContentResolver() != null
) {
538 getContentResolver().applyBatch(ProviderMeta
.AUTHORITY_FILES
, operations
);
541 getContentProvider().applyBatch(operations
);
544 } catch (OperationApplicationException e
) {
545 Log
.e(TAG
, "Fail to update descendants of " + dir
.getFileId() + " in database", e
);
547 } catch (RemoteException e
) {
548 Log
.e(TAG
, "Fail to update desendants of " + dir
.getFileId() + " in database", e
);