Merge branch 'share_link_show_shared_files' into share_link__unshare_file
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / FileDataStorageManager.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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.Collection;
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.Vector;
27
28 import com.owncloud.android.MainApp;
29 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
30 import com.owncloud.android.lib.operations.common.OCShare;
31 import com.owncloud.android.lib.operations.common.ShareType;
32 import com.owncloud.android.utils.FileStorageUtils;
33 import com.owncloud.android.utils.Log_OC;
34
35
36 import android.accounts.Account;
37 import android.content.ContentProviderClient;
38 import android.content.ContentProviderOperation;
39 import android.content.ContentProviderResult;
40 import android.content.ContentResolver;
41 import android.content.ContentUris;
42 import android.content.ContentValues;
43 import android.content.OperationApplicationException;
44 import android.database.Cursor;
45 import android.net.Uri;
46 import android.os.RemoteException;
47
48 public class FileDataStorageManager {
49
50 public static final int ROOT_PARENT_ID = 0;
51
52 private ContentResolver mContentResolver;
53 private ContentProviderClient mContentProviderClient;
54 private Account mAccount;
55
56 private static String TAG = FileDataStorageManager.class.getSimpleName();
57
58
59 public FileDataStorageManager(Account account, ContentResolver cr) {
60 mContentProviderClient = null;
61 mContentResolver = cr;
62 mAccount = account;
63 }
64
65 public FileDataStorageManager(Account account, ContentProviderClient cp) {
66 mContentProviderClient = cp;
67 mContentResolver = null;
68 mAccount = account;
69 }
70
71
72 public void setAccount(Account account) {
73 mAccount = account;
74 }
75
76 public Account getAccount() {
77 return mAccount;
78 }
79
80 public void setContentResolver(ContentResolver cr) {
81 mContentResolver = cr;
82 }
83
84 public ContentResolver getContentResolver() {
85 return mContentResolver;
86 }
87
88 public void setContentProviderClient(ContentProviderClient cp) {
89 mContentProviderClient = cp;
90 }
91
92 public ContentProviderClient getContentProviderClient() {
93 return mContentProviderClient;
94 }
95
96
97 public OCFile getFileByPath(String path) {
98 Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
99 OCFile file = null;
100 if (c.moveToFirst()) {
101 file = createFileInstance(c);
102 }
103 c.close();
104 if (file == null && OCFile.ROOT_PATH.equals(path)) {
105 return createRootDir(); // root should always exist
106 }
107 return file;
108 }
109
110
111 public OCFile getFileById(long id) {
112 Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
113 OCFile file = null;
114 if (c.moveToFirst()) {
115 file = createFileInstance(c);
116 }
117 c.close();
118 return file;
119 }
120
121 public OCFile getFileByLocalPath(String path) {
122 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
123 OCFile file = null;
124 if (c.moveToFirst()) {
125 file = createFileInstance(c);
126 }
127 c.close();
128 return file;
129 }
130
131 public boolean fileExists(long id) {
132 return fileExists(ProviderTableMeta._ID, String.valueOf(id));
133 }
134
135 public boolean fileExists(String path) {
136 return fileExists(ProviderTableMeta.FILE_PATH, path);
137 }
138
139
140 public Vector<OCFile> getFolderContent(OCFile f) {
141 if (f != null && f.isFolder() && f.getFileId() != -1) {
142 return getFolderContent(f.getFileId());
143
144 } else {
145 return new Vector<OCFile>();
146 }
147 }
148
149
150 public Vector<OCFile> getFolderImages(OCFile folder) {
151 Vector<OCFile> ret = new Vector<OCFile>();
152 if (folder != null) {
153 // TODO better implementation, filtering in the access to database (if possible) instead of here
154 Vector<OCFile> tmp = getFolderContent(folder);
155 OCFile current = null;
156 for (int i=0; i<tmp.size(); i++) {
157 current = tmp.get(i);
158 if (current.isImage()) {
159 ret.add(current);
160 }
161 }
162 }
163 return ret;
164 }
165
166
167 public boolean saveFile(OCFile file) {
168 boolean overriden = false;
169 ContentValues cv = new ContentValues();
170 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
171 cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
172 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
173 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
174 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
175 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
176 //if (file.getParentId() != DataStorageManager.ROOT_PARENT_ID)
177 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
178 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
179 if (!file.isFolder())
180 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
181 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
182 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
183 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
184 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
185 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
186 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
187 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
188
189 boolean sameRemotePath = fileExists(file.getRemotePath());
190 if (sameRemotePath ||
191 fileExists(file.getFileId()) ) { // for renamed files; no more delete and create
192
193 OCFile oldFile = null;
194 if (sameRemotePath) {
195 oldFile = getFileByPath(file.getRemotePath());
196 file.setFileId(oldFile.getFileId());
197 } else {
198 oldFile = getFileById(file.getFileId());
199 }
200
201 overriden = true;
202 if (getContentResolver() != null) {
203 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
204 ProviderTableMeta._ID + "=?",
205 new String[] { String.valueOf(file.getFileId()) });
206 } else {
207 try {
208 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI,
209 cv, ProviderTableMeta._ID + "=?",
210 new String[] { String.valueOf(file.getFileId()) });
211 } catch (RemoteException e) {
212 Log_OC.e(TAG,
213 "Fail to insert insert file to database "
214 + e.getMessage());
215 }
216 }
217 } else {
218 Uri result_uri = null;
219 if (getContentResolver() != null) {
220 result_uri = getContentResolver().insert(
221 ProviderTableMeta.CONTENT_URI_FILE, cv);
222 } else {
223 try {
224 result_uri = getContentProviderClient().insert(
225 ProviderTableMeta.CONTENT_URI_FILE, cv);
226 } catch (RemoteException e) {
227 Log_OC.e(TAG,
228 "Fail to insert insert file to database "
229 + e.getMessage());
230 }
231 }
232 if (result_uri != null) {
233 long new_id = Long.parseLong(result_uri.getPathSegments()
234 .get(1));
235 file.setFileId(new_id);
236 }
237 }
238
239 if (file.isFolder()) {
240 updateFolderSize(file.getFileId());
241 } else {
242 updateFolderSize(file.getParentId());
243 }
244
245 return overriden;
246 }
247
248
249 /**
250 * Inserts or updates the list of files contained in a given folder.
251 *
252 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
253 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
254 *
255 * @param folder
256 * @param files
257 * @param removeNotUpdated
258 */
259 public void saveFolder(OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove) {
260
261 Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size() + " children and " + filesToRemove.size() + " files to remove");
262
263 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(updatedFiles.size());
264
265 // prepare operations to insert or update files to save in the given folder
266 for (OCFile file : updatedFiles) {
267 ContentValues cv = new ContentValues();
268 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
269 cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
270 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
271 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
272 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
273 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
274 //cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
275 cv.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
276 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
277 if (!file.isFolder()) {
278 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
279 }
280 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
281 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
282 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
283 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
284 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
285 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
286 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
287
288 boolean existsByPath = fileExists(file.getRemotePath());
289 if (existsByPath || fileExists(file.getFileId())) {
290 // updating an existing file
291 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
292 withValues(cv).
293 withSelection( ProviderTableMeta._ID + "=?",
294 new String[] { String.valueOf(file.getFileId()) })
295 .build());
296
297 } else {
298 // adding a new file
299 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
300 }
301 }
302
303 // prepare operations to remove files in the given folder
304 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
305 String [] whereArgs = null;
306 for (OCFile file : filesToRemove) {
307 if (file.getParentId() == folder.getFileId()) {
308 whereArgs = new String[]{mAccount.name, file.getRemotePath()};
309 //Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, "" + file.getFileId());
310 if (file.isFolder()) {
311 operations.add(ContentProviderOperation
312 .newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, file.getFileId())).withSelection(where, whereArgs)
313 .build());
314 // TODO remove local folder
315 } else {
316 operations.add(ContentProviderOperation
317 .newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId())).withSelection(where, whereArgs)
318 .build());
319 if (file.isDown()) {
320 new File(file.getStoragePath()).delete();
321 // TODO move the deletion of local contents after success of deletions
322 }
323 }
324 }
325 }
326
327 // update metadata of folder
328 ContentValues cv = new ContentValues();
329 cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
330 cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, folder.getModificationTimestampAtLastSyncForData());
331 cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
332 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, 0); // FileContentProvider calculates the right size
333 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
334 cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
335 cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
336 cv.put(ProviderTableMeta.FILE_PATH, folder.getRemotePath());
337 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
338 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.getLastSyncDateForProperties());
339 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.getLastSyncDateForData());
340 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, folder.keepInSync() ? 1 : 0);
341 cv.put(ProviderTableMeta.FILE_ETAG, folder.getEtag());
342 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, folder.isShareByLink() ? 1 : 0);
343 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, folder.getPublicLink());
344
345 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
346 withValues(cv).
347 withSelection( ProviderTableMeta._ID + "=?",
348 new String[] { String.valueOf(folder.getFileId()) })
349 .build());
350
351 // apply operations in batch
352 ContentProviderResult[] results = null;
353 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
354 try {
355 if (getContentResolver() != null) {
356 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
357
358 } else {
359 results = getContentProviderClient().applyBatch(operations);
360 }
361
362 } catch (OperationApplicationException e) {
363 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
364
365 } catch (RemoteException e) {
366 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
367 }
368
369 // update new id in file objects for insertions
370 if (results != null) {
371 long newId;
372 Iterator<OCFile> filesIt = updatedFiles.iterator();
373 OCFile file = null;
374 for (int i=0; i<results.length; i++) {
375 if (filesIt.hasNext()) {
376 file = filesIt.next();
377 } else {
378 file = null;
379 }
380 if (results[i].uri != null) {
381 newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
382 //updatedFiles.get(i).setFileId(newId);
383 if (file != null) {
384 file.setFileId(newId);
385 }
386 }
387 }
388 }
389
390 updateFolderSize(folder.getFileId());
391
392 }
393
394
395 /**
396 *
397 * @param id
398 */
399 private void updateFolderSize(long id) {
400 if (id > FileDataStorageManager.ROOT_PARENT_ID) {
401 Log_OC.d(TAG, "Updating size of " + id);
402 if (getContentResolver() != null) {
403 getContentResolver().update(ProviderTableMeta.CONTENT_URI_DIR,
404 new ContentValues(), // won't be used, but cannot be null; crashes in KLP
405 ProviderTableMeta._ID + "=?",
406 new String[] { String.valueOf(id) });
407 } else {
408 try {
409 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_DIR,
410 new ContentValues(), // won't be used, but cannot be null; crashes in KLP
411 ProviderTableMeta._ID + "=?",
412 new String[] { String.valueOf(id) });
413
414 } catch (RemoteException e) {
415 Log_OC.e(TAG, "Exception in update of folder size through compatibility patch " + e.getMessage());
416 }
417 }
418 } else {
419 Log_OC.e(TAG, "not updating size for folder " + id);
420 }
421 }
422
423
424 public void removeFile(OCFile file, boolean removeDBData, boolean removeLocalCopy) {
425 if (file != null) {
426 if (file.isFolder()) {
427 removeFolder(file, removeDBData, removeLocalCopy);
428
429 } else {
430 if (removeDBData) {
431 //Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
432 Uri file_uri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId());
433 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
434 String [] whereArgs = new String[]{mAccount.name, file.getRemotePath()};
435 if (getContentProviderClient() != null) {
436 try {
437 getContentProviderClient().delete(file_uri, where, whereArgs);
438 } catch (RemoteException e) {
439 e.printStackTrace();
440 }
441 } else {
442 getContentResolver().delete(file_uri, where, whereArgs);
443 }
444 updateFolderSize(file.getParentId());
445 }
446 if (removeLocalCopy && file.isDown() && file.getStoragePath() != null) {
447 boolean success = new File(file.getStoragePath()).delete();
448 if (!removeDBData && success) {
449 // maybe unnecessary, but should be checked TODO remove if unnecessary
450 file.setStoragePath(null);
451 saveFile(file);
452 }
453 }
454 }
455 }
456 }
457
458
459 public void removeFolder(OCFile folder, boolean removeDBData, boolean removeLocalContent) {
460 if (folder != null && folder.isFolder()) {
461 if (removeDBData && folder.getFileId() != -1) {
462 removeFolderInDb(folder);
463 }
464 if (removeLocalContent) {
465 File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, folder));
466 removeLocalFolder(localFolder);
467 }
468 }
469 }
470
471 private void removeFolderInDb(OCFile folder) {
472 Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, ""+ folder.getFileId()); // URI for recursive deletion
473 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
474 String [] whereArgs = new String[]{mAccount.name, folder.getRemotePath()};
475 if (getContentProviderClient() != null) {
476 try {
477 getContentProviderClient().delete(folder_uri, where, whereArgs);
478 } catch (RemoteException e) {
479 e.printStackTrace();
480 }
481 } else {
482 getContentResolver().delete(folder_uri, where, whereArgs);
483 }
484 updateFolderSize(folder.getParentId());
485 }
486
487 private void removeLocalFolder(File folder) {
488 if (folder.exists()) {
489 File[] files = folder.listFiles();
490 if (files != null) {
491 for (File file : files) {
492 if (file.isDirectory()) {
493 removeLocalFolder(file);
494 } else {
495 file.delete();
496 }
497 }
498 }
499 folder.delete();
500 }
501 }
502
503 /**
504 * Updates database for a folder that was moved to a different location.
505 *
506 * TODO explore better (faster) implementations
507 * TODO throw exceptions up !
508 */
509 public void moveFolder(OCFile folder, String newPath) {
510 // TODO check newPath
511
512 if (folder != null && folder.isFolder() && folder.fileExists() && !OCFile.ROOT_PATH.equals(folder.getFileName())) {
513 /// 1. get all the descendants of 'dir' in a single QUERY (including 'dir')
514 Cursor c = null;
515 if (getContentProviderClient() != null) {
516 try {
517 c = getContentProviderClient().query(ProviderTableMeta.CONTENT_URI,
518 null,
519 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
520 new String[] { mAccount.name, folder.getRemotePath() + "%" }, ProviderTableMeta.FILE_PATH + " ASC ");
521 } catch (RemoteException e) {
522 Log_OC.e(TAG, e.getMessage());
523 }
524 } else {
525 c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
526 null,
527 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
528 new String[] { mAccount.name, folder.getRemotePath() + "%" }, ProviderTableMeta.FILE_PATH + " ASC ");
529 }
530
531 /// 2. prepare a batch of update operations to change all the descendants
532 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(c.getCount());
533 int lengthOfOldPath = folder.getRemotePath().length();
534 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
535 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
536 if (c.moveToFirst()) {
537 do {
538 ContentValues cv = new ContentValues(); // don't take the constructor out of the loop and clear the object
539 OCFile child = createFileInstance(c);
540 cv.put(ProviderTableMeta.FILE_PATH, newPath + child.getRemotePath().substring(lengthOfOldPath));
541 if (child.getStoragePath() != null && child.getStoragePath().startsWith(defaultSavePath)) {
542 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, defaultSavePath + newPath + child.getStoragePath().substring(lengthOfOldStoragePath));
543 }
544 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
545 withValues(cv).
546 withSelection( ProviderTableMeta._ID + "=?",
547 new String[] { String.valueOf(child.getFileId()) })
548 .build());
549 } while (c.moveToNext());
550 }
551 c.close();
552
553 /// 3. apply updates in batch
554 try {
555 if (getContentResolver() != null) {
556 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
557
558 } else {
559 getContentProviderClient().applyBatch(operations);
560 }
561
562 } catch (OperationApplicationException e) {
563 Log_OC.e(TAG, "Fail to update descendants of " + folder.getFileId() + " in database", e);
564
565 } catch (RemoteException e) {
566 Log_OC.e(TAG, "Fail to update desendants of " + folder.getFileId() + " in database", e);
567 }
568
569 }
570 }
571
572
573 private Vector<OCFile> getFolderContent(long parentId) {
574
575 Vector<OCFile> ret = new Vector<OCFile>();
576
577 Uri req_uri = Uri.withAppendedPath(
578 ProviderTableMeta.CONTENT_URI_DIR,
579 String.valueOf(parentId));
580 Cursor c = null;
581
582 if (getContentProviderClient() != null) {
583 try {
584 c = getContentProviderClient().query(req_uri, null,
585 ProviderTableMeta.FILE_PARENT + "=?" ,
586 new String[] { String.valueOf(parentId)}, null);
587 } catch (RemoteException e) {
588 Log_OC.e(TAG, e.getMessage());
589 return ret;
590 }
591 } else {
592 c = getContentResolver().query(req_uri, null,
593 ProviderTableMeta.FILE_PARENT + "=?" ,
594 new String[] { String.valueOf(parentId)}, null);
595 }
596
597 if (c.moveToFirst()) {
598 do {
599 OCFile child = createFileInstance(c);
600 ret.add(child);
601 } while (c.moveToNext());
602 }
603
604 c.close();
605
606 Collections.sort(ret);
607
608 return ret;
609 }
610
611
612 private OCFile createRootDir() {
613 OCFile file = new OCFile(OCFile.ROOT_PATH);
614 file.setMimetype("DIR");
615 file.setParentId(FileDataStorageManager.ROOT_PARENT_ID);
616 saveFile(file);
617 return file;
618 }
619
620 private boolean fileExists(String cmp_key, String value) {
621 Cursor c;
622 if (getContentResolver() != null) {
623 c = getContentResolver()
624 .query(ProviderTableMeta.CONTENT_URI,
625 null,
626 cmp_key + "=? AND "
627 + ProviderTableMeta.FILE_ACCOUNT_OWNER
628 + "=?",
629 new String[] { value, mAccount.name }, null);
630 } else {
631 try {
632 c = getContentProviderClient().query(
633 ProviderTableMeta.CONTENT_URI,
634 null,
635 cmp_key + "=? AND "
636 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
637 new String[] { value, mAccount.name }, null);
638 } catch (RemoteException e) {
639 Log_OC.e(TAG,
640 "Couldn't determine file existance, assuming non existance: "
641 + e.getMessage());
642 return false;
643 }
644 }
645 boolean retval = c.moveToFirst();
646 c.close();
647 return retval;
648 }
649
650 private Cursor getCursorForValue(String key, String value) {
651 Cursor c = null;
652 if (getContentResolver() != null) {
653 c = getContentResolver()
654 .query(ProviderTableMeta.CONTENT_URI,
655 null,
656 key + "=? AND "
657 + ProviderTableMeta.FILE_ACCOUNT_OWNER
658 + "=?",
659 new String[] { value, mAccount.name }, null);
660 } else {
661 try {
662 c = getContentProviderClient().query(
663 ProviderTableMeta.CONTENT_URI,
664 null,
665 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
666 + "=?", new String[] { value, mAccount.name },
667 null);
668 } catch (RemoteException e) {
669 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
670 c = null;
671 }
672 }
673 return c;
674 }
675
676 private Cursor getShareCursorForValue(String key, String value) {
677 Cursor c = null;
678 if (getContentResolver() != null) {
679 c = getContentResolver()
680 .query(ProviderTableMeta.CONTENT_URI_SHARE,
681 null,
682 key + "=? AND "
683 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
684 + "=?",
685 new String[] { value, mAccount.name }, null);
686 } else {
687 try {
688 c = getContentProviderClient().query(
689 ProviderTableMeta.CONTENT_URI_SHARE,
690 null,
691 key + "=? AND " + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
692 + "=?", new String[] { value, mAccount.name },
693 null);
694 } catch (RemoteException e) {
695 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
696 c = null;
697 }
698 }
699 return c;
700 }
701
702 private OCFile createFileInstance(Cursor c) {
703 OCFile file = null;
704 if (c != null) {
705 file = new OCFile(c.getString(c
706 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
707 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
708 file.setParentId(c.getLong(c
709 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
710 file.setMimetype(c.getString(c
711 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
712 if (!file.isFolder()) {
713 file.setStoragePath(c.getString(c
714 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
715 if (file.getStoragePath() == null) {
716 // 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
717 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
718 if (f.exists()) {
719 file.setStoragePath(f.getAbsolutePath());
720 file.setLastSyncDateForData(f.lastModified());
721 }
722 }
723 }
724 file.setFileLength(c.getLong(c
725 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
726 file.setCreationTimestamp(c.getLong(c
727 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
728 file.setModificationTimestamp(c.getLong(c
729 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
730 file.setModificationTimestampAtLastSyncForData(c.getLong(c
731 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)));
732 file.setLastSyncDateForProperties(c.getLong(c
733 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
734 file.setLastSyncDateForData(c.getLong(c.
735 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
736 file.setKeepInSync(c.getInt(
737 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
738 file.setEtag(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)));
739 file.setShareByLink(c.getInt(
740 c.getColumnIndex(ProviderTableMeta.FILE_SHARE_BY_LINK)) == 1 ? true : false);
741 file.setPublicLink(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PUBLIC_LINK)));
742
743 }
744 return file;
745 }
746
747 /**
748 * Returns if the file/folder is shared by link or not
749 * @param path Path of the file/folder
750 * @return
751 */
752 public boolean isShareByLink(String path) {
753 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
754 OCFile file = null;
755 if (c.moveToFirst()) {
756 file = createFileInstance(c);
757 }
758 c.close();
759 return file.isShareByLink();
760 }
761
762 /**
763 * Returns the public link of the file/folder
764 * @param path Path of the file/folder
765 * @return
766 */
767 public String getPublicLink(String path) {
768 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
769 OCFile file = null;
770 if (c.moveToFirst()) {
771 file = createFileInstance(c);
772 }
773 c.close();
774 return file.getPublicLink();
775 }
776
777
778 // Methods for Shares
779 public boolean saveShare(OCShare share) {
780 boolean overriden = false;
781 ContentValues cv = new ContentValues();
782 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
783 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
784 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
785 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
786 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
787 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
788 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
789 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
790 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
791 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, share.getSharedWithDisplayName());
792 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isDirectory() ? 1 : 0);
793 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
794 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
795 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
796
797 boolean samePath = shareExists(share.getPath());
798 if (samePath ||
799 shareExists(share.getId())) { // for renamed files; no more delete and create
800
801 OCShare oldFile = null;
802 if (samePath) {
803 oldFile = getShareByPath(share.getPath());
804 share.setId(oldFile.getId());
805 } else {
806 oldFile = getShareById(share.getId());
807 }
808
809 overriden = true;
810 if (getContentResolver() != null) {
811 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
812 ProviderTableMeta._ID + "=?",
813 new String[] { String.valueOf(share.getId()) });
814 } else {
815 try {
816 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
817 cv, ProviderTableMeta._ID + "=?",
818 new String[] { String.valueOf(share.getId()) });
819 } catch (RemoteException e) {
820 Log_OC.e(TAG,
821 "Fail to insert insert file to database "
822 + e.getMessage());
823 }
824 }
825 } else {
826 Uri result_uri = null;
827 if (getContentResolver() != null) {
828 result_uri = getContentResolver().insert(
829 ProviderTableMeta.CONTENT_URI_SHARE, cv);
830 } else {
831 try {
832 result_uri = getContentProviderClient().insert(
833 ProviderTableMeta.CONTENT_URI_SHARE, cv);
834 } catch (RemoteException e) {
835 Log_OC.e(TAG,
836 "Fail to insert insert file to database "
837 + e.getMessage());
838 }
839 }
840 if (result_uri != null) {
841 long new_id = Long.parseLong(result_uri.getPathSegments()
842 .get(1));
843 share.setId(new_id);
844 }
845 }
846
847 return overriden;
848 }
849
850 private OCShare getShareById(long id) {
851 Cursor c = getShareCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
852 OCShare share = null;
853 if (c.moveToFirst()) {
854 share = createShareInstance(c);
855 }
856 c.close();
857 return share;
858 }
859
860 public OCShare getShareByPath(String path) {
861 Cursor c = getShareCursorForValue(ProviderTableMeta.OCSHARES_PATH, path);
862 OCShare share = null;
863 if (c.moveToFirst()) {
864 share = createShareInstance(c);
865 }
866 c.close();
867 return share;
868 }
869
870 private OCShare createShareInstance(Cursor c) {
871 OCShare share = null;
872 if (c != null) {
873 share = new OCShare(c.getString(c
874 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
875 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
876 share.setFileSource(c.getLong(c
877 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
878 share.setShareType(ShareType.fromValue(c.getInt(c
879 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
880 share.setPermissions(c.getInt(c
881 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
882 share.setSharedDate(c.getLong(c
883 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
884 share.setExpirationDate(c.getLong(c
885 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
886 share.setToken(c.getString(c
887 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
888 share.setSharedWithDisplayName(c.getString(c
889 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
890 share.setIsDirectory(c.getInt(
891 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1 ? true : false);
892 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
893 share.setIdRemoteShared(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED)));
894
895 }
896 return share;
897 }
898
899 private boolean shareExists(String cmp_key, String value) {
900 Cursor c;
901 if (getContentResolver() != null) {
902 c = getContentResolver()
903 .query(ProviderTableMeta.CONTENT_URI_SHARE,
904 null,
905 cmp_key + "=? AND "
906 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
907 + "=?",
908 new String[] { value, mAccount.name }, null);
909 } else {
910 try {
911 c = getContentProviderClient().query(
912 ProviderTableMeta.CONTENT_URI_SHARE,
913 null,
914 cmp_key + "=? AND "
915 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
916 new String[] { value, mAccount.name }, null);
917 } catch (RemoteException e) {
918 Log_OC.e(TAG,
919 "Couldn't determine file existance, assuming non existance: "
920 + e.getMessage());
921 return false;
922 }
923 }
924 boolean retval = c.moveToFirst();
925 c.close();
926 return retval;
927 }
928
929 public boolean shareExists(long id) {
930 return shareExists(ProviderTableMeta._ID, String.valueOf(id));
931 }
932
933 public boolean shareExists(String path) {
934 return shareExists(ProviderTableMeta.OCSHARES_PATH, path);
935 }
936
937 private void cleanSharedFiles() {
938 ContentValues cv = new ContentValues();
939 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
940 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
941 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
942 String [] whereArgs = new String[]{mAccount.name};
943
944 if (getContentResolver() != null) {
945 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
946
947 } else {
948 try {
949 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
950
951 } catch (RemoteException e) {
952 Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
953 }
954 }
955 }
956
957 private void cleanShares() {
958 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
959 String [] whereArgs = new String[]{mAccount.name};
960
961 if (getContentResolver() != null) {
962 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
963
964 } else {
965 try {
966 getContentProviderClient().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
967
968 } catch (RemoteException e) {
969 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
970 }
971 }
972 }
973
974 public void saveShares(Collection<OCShare> shares) {
975 cleanShares();
976 if (shares != null) {
977 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(shares.size());
978
979 // prepare operations to insert or update files to save in the given folder
980 for (OCShare share : shares) {
981 ContentValues cv = new ContentValues();
982 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
983 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
984 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
985 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
986 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
987 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
988 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
989 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
990 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
991 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, share.getSharedWithDisplayName());
992 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isDirectory() ? 1 : 0);
993 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
994 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
995 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
996
997 boolean existsByPath = shareExists(share.getPath());
998 if (existsByPath || shareExists(share.getId())) {
999 // updating an existing file
1000 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1001 withValues(cv).
1002 withSelection( ProviderTableMeta._ID + "=?",
1003 new String[] { String.valueOf(share.getId()) })
1004 .build());
1005
1006 } else {
1007 // adding a new file
1008 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).withValues(cv).build());
1009 }
1010 }
1011
1012 // apply operations in batch
1013 if (operations.size() > 0) {
1014 @SuppressWarnings("unused")
1015 ContentProviderResult[] results = null;
1016 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1017 try {
1018 if (getContentResolver() != null) {
1019 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1020
1021 } else {
1022 results = getContentProviderClient().applyBatch(operations);
1023 }
1024
1025 } catch (OperationApplicationException e) {
1026 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1027
1028 } catch (RemoteException e) {
1029 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1030 }
1031 }
1032 }
1033
1034 }
1035
1036 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1037 cleanSharedFiles();
1038
1039 if (sharedFiles != null) {
1040 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(sharedFiles.size());
1041
1042 // prepare operations to insert or update files to save in the given folder
1043 for (OCFile file : sharedFiles) {
1044 ContentValues cv = new ContentValues();
1045 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1046 cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
1047 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1048 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1049 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1050 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1051 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1052 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1053 if (!file.isFolder()) {
1054 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1055 }
1056 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1057 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1058 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
1059 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
1060 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1061 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
1062 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1063
1064 boolean existsByPath = fileExists(file.getRemotePath());
1065 if (existsByPath || fileExists(file.getFileId())) {
1066 // updating an existing file
1067 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1068 withValues(cv).
1069 withSelection( ProviderTableMeta._ID + "=?",
1070 new String[] { String.valueOf(file.getFileId()) })
1071 .build());
1072
1073 } else {
1074 // adding a new file
1075 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
1076 }
1077 }
1078
1079 // apply operations in batch
1080 if (operations.size() > 0) {
1081 @SuppressWarnings("unused")
1082 ContentProviderResult[] results = null;
1083 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1084 try {
1085 if (getContentResolver() != null) {
1086 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1087
1088 } else {
1089 results = getContentProviderClient().applyBatch(operations);
1090 }
1091
1092 } catch (OperationApplicationException e) {
1093 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1094
1095 } catch (RemoteException e) {
1096 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1097 }
1098 }
1099 }
1100
1101 }
1102
1103 public void removeShare(OCShare share){
1104 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1105 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
1106 String [] whereArgs = new String[]{mAccount.name, share.getPath()};
1107 if (getContentProviderClient() != null) {
1108 try {
1109 getContentProviderClient().delete(share_uri, where, whereArgs);
1110 } catch (RemoteException e) {
1111 e.printStackTrace();
1112 }
1113 } else {
1114 getContentResolver().delete(share_uri, where, whereArgs);
1115 }
1116 }
1117 }