Merge remote-tracking branch 'remotes/upstream/resizedImages' into beta
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / FileDataStorageManager.java
1 /**
2 * ownCloud Android client application
3 *
4 * Copyright (C) 2012 Bartek Przybylski
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.datamodel;
22
23 import java.io.File;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.Vector;
32
33 import android.accounts.Account;
34 import android.content.ContentProviderClient;
35 import android.content.ContentProviderOperation;
36 import android.content.ContentProviderResult;
37 import android.content.ContentResolver;
38 import android.content.ContentUris;
39 import android.content.ContentValues;
40 import android.content.Intent;
41 import android.content.OperationApplicationException;
42 import android.database.Cursor;
43 import android.net.Uri;
44 import android.os.RemoteException;
45 import android.provider.MediaStore;
46
47 import com.owncloud.android.MainApp;
48 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
49 import com.owncloud.android.lib.common.utils.Log_OC;
50 import com.owncloud.android.lib.resources.shares.OCShare;
51 import com.owncloud.android.lib.resources.shares.ShareType;
52 import com.owncloud.android.lib.resources.status.CapabilityBooleanType;
53 import com.owncloud.android.lib.resources.status.OCCapability;
54 import com.owncloud.android.utils.FileStorageUtils;
55
56 public class FileDataStorageManager {
57
58 public static final int ROOT_PARENT_ID = 0;
59
60 private ContentResolver mContentResolver;
61 private ContentProviderClient mContentProviderClient;
62 private Account mAccount;
63
64 private static String TAG = FileDataStorageManager.class.getSimpleName();
65
66
67 public FileDataStorageManager(Account account, ContentResolver cr) {
68 mContentProviderClient = null;
69 mContentResolver = cr;
70 mAccount = account;
71 }
72
73 public FileDataStorageManager(Account account, ContentProviderClient cp) {
74 mContentProviderClient = cp;
75 mContentResolver = null;
76 mAccount = account;
77 }
78
79
80 public void setAccount(Account account) {
81 mAccount = account;
82 }
83
84 public Account getAccount() {
85 return mAccount;
86 }
87
88 public ContentResolver getContentResolver() {
89 return mContentResolver;
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, boolean onlyOnDevice) {
141 if (f != null && f.isFolder() && f.getFileId() != -1) {
142 return getFolderContent(f.getFileId(), onlyOnDevice);
143
144 } else {
145 return new Vector<OCFile>();
146 }
147 }
148
149
150 public Vector<OCFile> getFolderImages(OCFile folder, boolean onlyOnDevice) {
151 Vector<OCFile> ret = new Vector<OCFile>();
152 if (folder != null) {
153 // TODO better implementation, filtering in the access to database instead of here
154 Vector<OCFile> tmp = getFolderContent(folder, onlyOnDevice);
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 public boolean saveFile(OCFile file) {
167 boolean overriden = false;
168 ContentValues cv = new ContentValues();
169 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
170 cv.put(
171 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
172 file.getModificationTimestampAtLastSyncForData()
173 );
174 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
175 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
176 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
177 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
178 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
179 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
180 if (!file.isFolder())
181 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
182 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
183 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
184 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
185 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.isFavorite() ? 1 : 0);
186 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
187 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
188 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
189 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
190 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
191 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
192 cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
193 cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
194 cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
195
196 boolean sameRemotePath = fileExists(file.getRemotePath());
197 if (sameRemotePath ||
198 fileExists(file.getFileId())) { // for renamed files; no more delete and create
199
200 OCFile oldFile;
201 if (sameRemotePath) {
202 oldFile = getFileByPath(file.getRemotePath());
203 file.setFileId(oldFile.getFileId());
204 } else {
205 oldFile = getFileById(file.getFileId());
206 }
207
208 overriden = true;
209 if (getContentResolver() != null) {
210 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
211 ProviderTableMeta._ID + "=?",
212 new String[]{String.valueOf(file.getFileId())});
213 } else {
214 try {
215 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI,
216 cv, ProviderTableMeta._ID + "=?",
217 new String[]{String.valueOf(file.getFileId())});
218 } catch (RemoteException e) {
219 Log_OC.e(TAG,
220 "Fail to insert insert file to database "
221 + e.getMessage());
222 }
223 }
224 } else {
225 Uri result_uri = null;
226 if (getContentResolver() != null) {
227 result_uri = getContentResolver().insert(
228 ProviderTableMeta.CONTENT_URI_FILE, cv);
229 } else {
230 try {
231 result_uri = getContentProviderClient().insert(
232 ProviderTableMeta.CONTENT_URI_FILE, cv);
233 } catch (RemoteException e) {
234 Log_OC.e(TAG,
235 "Fail to insert insert file to database "
236 + e.getMessage());
237 }
238 }
239 if (result_uri != null) {
240 long new_id = Long.parseLong(result_uri.getPathSegments()
241 .get(1));
242 file.setFileId(new_id);
243 }
244 }
245
246 return overriden;
247 }
248
249
250 /**
251 * Inserts or updates the list of files contained in a given folder.
252 * <p/>
253 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
254 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
255 *
256 * @param folder
257 * @param updatedFiles
258 * @param filesToRemove
259 */
260 public void saveFolder(
261 OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove
262 ) {
263
264 Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size()
265 + " children and " + filesToRemove.size() + " files to remove");
266
267 ArrayList<ContentProviderOperation> operations =
268 new ArrayList<ContentProviderOperation>(updatedFiles.size());
269
270 // prepare operations to insert or update files to save in the given folder
271 for (OCFile file : updatedFiles) {
272 ContentValues cv = new ContentValues();
273 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
274 cv.put(
275 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
276 file.getModificationTimestampAtLastSyncForData()
277 );
278 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
279 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
280 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
281 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
282 //cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
283 cv.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
284 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
285 if (!file.isFolder()) {
286 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
287 }
288 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
289 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
290 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
291 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.isFavorite() ? 1 : 0);
292 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
293 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
294 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
295 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
296 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
297 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
298 cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
299 cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
300 cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
301
302 boolean existsByPath = fileExists(file.getRemotePath());
303 if (existsByPath || fileExists(file.getFileId())) {
304 // updating an existing file
305 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
306 withValues(cv).
307 withSelection(ProviderTableMeta._ID + "=?",
308 new String[]{String.valueOf(file.getFileId())})
309 .build());
310
311 } else {
312 // adding a new file
313 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
314 withValues(cv).build());
315 }
316 }
317
318 // prepare operations to remove files in the given folder
319 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
320 ProviderTableMeta.FILE_PATH + "=?";
321 String [] whereArgs = null;
322 for (OCFile file : filesToRemove) {
323 if (file.getParentId() == folder.getFileId()) {
324 whereArgs = new String[]{mAccount.name, file.getRemotePath()};
325 if (file.isFolder()) {
326 operations.add(ContentProviderOperation.newDelete(
327 ContentUris.withAppendedId(
328 ProviderTableMeta.CONTENT_URI_DIR, file.getFileId()
329 )
330 ).withSelection(where, whereArgs).build());
331
332 File localFolder =
333 new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
334 if (localFolder.exists()) {
335 removeLocalFolder(localFolder);
336 }
337 } else {
338 operations.add(ContentProviderOperation.newDelete(
339 ContentUris.withAppendedId(
340 ProviderTableMeta.CONTENT_URI_FILE, file.getFileId()
341 )
342 ).withSelection(where, whereArgs).build());
343
344 if (file.isDown()) {
345 String path = file.getStoragePath();
346 new File(path).delete();
347 triggerMediaScan(path); // notify MediaScanner about removed file
348 }
349 }
350 }
351 }
352
353 // update metadata of folder
354 ContentValues cv = new ContentValues();
355 cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
356 cv.put(
357 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
358 folder.getModificationTimestampAtLastSyncForData()
359 );
360 cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
361 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, 0);
362 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
363 cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
364 cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
365 cv.put(ProviderTableMeta.FILE_PATH, folder.getRemotePath());
366 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
367 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.getLastSyncDateForProperties());
368 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.getLastSyncDateForData());
369 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, folder.isFavorite() ? 1 : 0);
370 cv.put(ProviderTableMeta.FILE_ETAG, folder.getEtag());
371 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, folder.isSharedViaLink() ? 1 : 0);
372 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, folder.isSharedWithSharee() ? 1 : 0);
373 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, folder.getPublicLink());
374 cv.put(ProviderTableMeta.FILE_PERMISSIONS, folder.getPermissions());
375 cv.put(ProviderTableMeta.FILE_REMOTE_ID, folder.getRemoteId());
376
377 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
378 withValues(cv).
379 withSelection(ProviderTableMeta._ID + "=?",
380 new String[]{String.valueOf(folder.getFileId())})
381 .build());
382
383 // apply operations in batch
384 ContentProviderResult[] results = null;
385 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
386 try {
387 if (getContentResolver() != null) {
388 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
389
390 } else {
391 results = getContentProviderClient().applyBatch(operations);
392 }
393
394 } catch (OperationApplicationException e) {
395 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
396
397 } catch (RemoteException e) {
398 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
399 }
400
401 // update new id in file objects for insertions
402 if (results != null) {
403 long newId;
404 Iterator<OCFile> filesIt = updatedFiles.iterator();
405 OCFile file = null;
406 for (int i = 0; i < results.length; i++) {
407 if (filesIt.hasNext()) {
408 file = filesIt.next();
409 } else {
410 file = null;
411 }
412 if (results[i].uri != null) {
413 newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
414 //updatedFiles.get(i).setFileId(newId);
415 if (file != null) {
416 file.setFileId(newId);
417 }
418 }
419 }
420 }
421
422 }
423
424
425 public boolean removeFile(OCFile file, boolean removeDBData, boolean removeLocalCopy) {
426 boolean success = true;
427 if (file != null) {
428 if (file.isFolder()) {
429 success = removeFolder(file, removeDBData, removeLocalCopy);
430
431 } else {
432 if (removeDBData) {
433 //Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE,
434 // ""+file.getFileId());
435 Uri file_uri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE,
436 file.getFileId());
437 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
438 ProviderTableMeta.FILE_PATH + "=?";
439 String[] whereArgs = new String[]{mAccount.name, file.getRemotePath()};
440 int deleted = 0;
441 if (getContentProviderClient() != null) {
442 try {
443 deleted = getContentProviderClient().delete(file_uri, where, whereArgs);
444 } catch (RemoteException e) {
445 e.printStackTrace();
446 }
447 } else {
448 deleted = getContentResolver().delete(file_uri, where, whereArgs);
449 }
450 success &= (deleted > 0);
451 }
452 String localPath = file.getStoragePath();
453 if (removeLocalCopy && file.isDown() && localPath != null && success) {
454 success = new File(localPath).delete();
455 if (success) {
456 deleteFileInMediaScan(localPath);
457 }
458 if (!removeDBData && success) {
459 // maybe unnecessary, but should be checked TODO remove if unnecessary
460 file.setStoragePath(null);
461 saveFile(file);
462 saveConflict(file, null);
463 }
464 }
465 }
466 }
467 return success;
468 }
469
470
471 public boolean removeFolder(OCFile folder, boolean removeDBData, boolean removeLocalContent) {
472 boolean success = true;
473 if (folder != null && folder.isFolder()) {
474 if (removeDBData && folder.getFileId() != -1) {
475 success = removeFolderInDb(folder);
476 }
477 if (removeLocalContent && success) {
478 success = removeLocalFolder(folder);
479 }
480 }
481 return success;
482 }
483
484 private boolean removeFolderInDb(OCFile folder) {
485 Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" +
486 folder.getFileId()); // URI for recursive deletion
487 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
488 ProviderTableMeta.FILE_PATH + "=?";
489 String [] whereArgs = new String[]{mAccount.name, folder.getRemotePath()};
490 int deleted = 0;
491 if (getContentProviderClient() != null) {
492 try {
493 deleted = getContentProviderClient().delete(folder_uri, where, whereArgs);
494 } catch (RemoteException e) {
495 e.printStackTrace();
496 }
497 } else {
498 deleted = getContentResolver().delete(folder_uri, where, whereArgs);
499 }
500 return deleted > 0;
501 }
502
503 private boolean removeLocalFolder(OCFile folder) {
504 boolean success = true;
505 String localFolderPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, folder);
506 File localFolder = new File(localFolderPath);
507 if (localFolder.exists()) {
508 // stage 1: remove the local files already registered in the files database
509 Vector<OCFile> files = getFolderContent(folder.getFileId(), false);
510 if (files != null) {
511 for (OCFile file : files) {
512 if (file.isFolder()) {
513 success &= removeLocalFolder(file);
514 } else {
515 if (file.isDown()) {
516 File localFile = new File(file.getStoragePath());
517 success &= localFile.delete();
518 if (success) {
519 // notify MediaScanner about removed file
520 deleteFileInMediaScan(file.getStoragePath());
521 file.setStoragePath(null);
522 saveFile(file);
523 }
524 }
525 }
526 }
527 }
528
529 // stage 2: remove the folder itself and any local file inside out of sync;
530 // for instance, after clearing the app cache or reinstalling
531 success &= removeLocalFolder(localFolder);
532 }
533 return success;
534 }
535
536 private boolean removeLocalFolder(File localFolder) {
537 boolean success = true;
538 File[] localFiles = localFolder.listFiles();
539 if (localFiles != null) {
540 for (File localFile : localFiles) {
541 if (localFile.isDirectory()) {
542 success &= removeLocalFolder(localFile);
543 } else {
544 String path = localFile.getAbsolutePath();
545 success &= localFile.delete();
546 }
547 }
548 }
549 success &= localFolder.delete();
550 return success;
551 }
552
553
554 /**
555 * Updates database and file system for a file or folder that was moved to a different location.
556 *
557 * TODO explore better (faster) implementations
558 * TODO throw exceptions up !
559 */
560 public void moveLocalFile(OCFile file, String targetPath, String targetParentPath) {
561
562 if (file != null && file.fileExists() && !OCFile.ROOT_PATH.equals(file.getFileName())) {
563
564 OCFile targetParent = getFileByPath(targetParentPath);
565 if (targetParent == null) {
566 throw new IllegalStateException(
567 "Parent folder of the target path does not exist!!");
568 }
569
570 /// 1. get all the descendants of the moved element in a single QUERY
571 Cursor c = null;
572 if (getContentProviderClient() != null) {
573 try {
574 c = getContentProviderClient().query(
575 ProviderTableMeta.CONTENT_URI,
576 null,
577 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
578 ProviderTableMeta.FILE_PATH + " LIKE ? ",
579 new String[]{
580 mAccount.name,
581 file.getRemotePath() + "%"
582 },
583 ProviderTableMeta.FILE_PATH + " ASC "
584 );
585 } catch (RemoteException e) {
586 Log_OC.e(TAG, e.getMessage());
587 }
588
589 } else {
590 c = getContentResolver().query(
591 ProviderTableMeta.CONTENT_URI,
592 null,
593 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
594 ProviderTableMeta.FILE_PATH + " LIKE ? ",
595 new String[]{
596 mAccount.name,
597 file.getRemotePath() + "%"
598 },
599 ProviderTableMeta.FILE_PATH + " ASC "
600 );
601 }
602
603 /// 2. prepare a batch of update operations to change all the descendants
604 ArrayList<ContentProviderOperation> operations =
605 new ArrayList<ContentProviderOperation>(c.getCount());
606 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
607 List<String> originalPathsToTriggerMediaScan = new ArrayList<String>();
608 List<String> newPathsToTriggerMediaScan = new ArrayList<String>();
609 if (c.moveToFirst()) {
610 int lengthOfOldPath = file.getRemotePath().length();
611 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
612 do {
613 ContentValues cv = new ContentValues(); // keep construction in the loop
614 OCFile child = createFileInstance(c);
615 cv.put(
616 ProviderTableMeta.FILE_PATH,
617 targetPath + child.getRemotePath().substring(lengthOfOldPath)
618 );
619 if (child.getStoragePath() != null &&
620 child.getStoragePath().startsWith(defaultSavePath)) {
621 // update link to downloaded content - but local move is not done here!
622 String targetLocalPath = defaultSavePath + targetPath +
623 child.getStoragePath().substring(lengthOfOldStoragePath);
624
625 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, targetLocalPath);
626
627 originalPathsToTriggerMediaScan.add(child.getStoragePath());
628 newPathsToTriggerMediaScan.add(targetLocalPath);
629
630 }
631 if (child.getRemotePath().equals(file.getRemotePath())) {
632 cv.put(
633 ProviderTableMeta.FILE_PARENT,
634 targetParent.getFileId()
635 );
636 }
637 operations.add(
638 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
639 withValues(cv).
640 withSelection(
641 ProviderTableMeta._ID + "=?",
642 new String[]{String.valueOf(child.getFileId())}
643 )
644 .build());
645
646 } while (c.moveToNext());
647 }
648 c.close();
649
650 /// 3. apply updates in batch
651 try {
652 if (getContentResolver() != null) {
653 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
654
655 } else {
656 getContentProviderClient().applyBatch(operations);
657 }
658
659 } catch (Exception e) {
660 Log_OC.e(TAG, "Fail to update " + file.getFileId() + " and descendants in database",
661 e);
662 }
663
664 /// 4. move in local file system
665 String originalLocalPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
666 String targetLocalPath = defaultSavePath + targetPath;
667 File localFile = new File(originalLocalPath);
668 boolean renamed = false;
669 if (localFile.exists()) {
670 File targetFile = new File(targetLocalPath);
671 File targetFolder = targetFile.getParentFile();
672 if (!targetFolder.exists()) {
673 targetFolder.mkdirs();
674 }
675 renamed = localFile.renameTo(targetFile);
676 }
677
678 if (renamed) {
679 Iterator<String> it = originalPathsToTriggerMediaScan.iterator();
680 while (it.hasNext()) {
681 // Notify MediaScanner about removed file
682 deleteFileInMediaScan(it.next());
683 }
684 it = newPathsToTriggerMediaScan.iterator();
685 while (it.hasNext()) {
686 // Notify MediaScanner about new file/folder
687 triggerMediaScan(it.next());
688 }
689 }
690 }
691
692 }
693
694 public void copyLocalFile(OCFile file, String targetPath) {
695
696 if (file != null && file.fileExists() && !OCFile.ROOT_PATH.equals(file.getFileName())) {
697 String localPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
698 File localFile = new File(localPath);
699 boolean copied = false;
700 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
701 if (localFile.exists()) {
702 File targetFile = new File(defaultSavePath + targetPath);
703 File targetFolder = targetFile.getParentFile();
704 if (!targetFolder.exists()) {
705 targetFolder.mkdirs();
706 }
707 copied = FileStorageUtils.copyFile(localFile, targetFile);
708 }
709 Log_OC.d(TAG, "Local file COPIED : " + copied);
710 }
711 }
712
713 public void migrateStoredFiles(String srcPath, String dstPath) throws Exception {
714 Cursor c = null;
715 if (getContentResolver() != null) {
716 c = getContentResolver().query(ProviderTableMeta.CONTENT_URI_FILE,
717 null,
718 ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL",
719 null,
720 null);
721
722 } else {
723 try {
724 c = getContentProviderClient().query(ProviderTableMeta.CONTENT_URI_FILE,
725 new String[]{ProviderTableMeta._ID, ProviderTableMeta.FILE_STORAGE_PATH},
726 ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL",
727 null,
728 null);
729 } catch (RemoteException e) {
730 Log_OC.e(TAG, e.getMessage());
731 throw e;
732 }
733 }
734
735 ArrayList<ContentProviderOperation> operations =
736 new ArrayList<ContentProviderOperation>(c.getCount());
737 if (c.moveToFirst()) {
738 do {
739 ContentValues cv = new ContentValues();
740 long fileId = c.getLong(c.getColumnIndex(ProviderTableMeta._ID));
741 String oldFileStoragePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
742
743 if (oldFileStoragePath.startsWith(srcPath)) {
744
745 cv.put(
746 ProviderTableMeta.FILE_STORAGE_PATH,
747 oldFileStoragePath.replaceFirst(srcPath, dstPath));
748
749 operations.add(
750 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
751 withValues(cv).
752 withSelection(
753 ProviderTableMeta._ID + "=?",
754 new String[]{String.valueOf(fileId)}
755 )
756 .build());
757 }
758
759 } while (c.moveToNext());
760 }
761 c.close();
762
763 /// 3. apply updates in batch
764 try {
765 if (getContentResolver() != null) {
766 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
767
768 } else {
769 getContentProviderClient().applyBatch(operations);
770 }
771
772 } catch (Exception e) {
773 throw e;
774 }
775 }
776
777
778 private Vector<OCFile> getFolderContent(long parentId, boolean onlyOnDevice) {
779
780 Vector<OCFile> ret = new Vector<OCFile>();
781
782 Uri req_uri = Uri.withAppendedPath(
783 ProviderTableMeta.CONTENT_URI_DIR,
784 String.valueOf(parentId));
785 Cursor c = null;
786
787 if (getContentProviderClient() != null) {
788 try {
789 c = getContentProviderClient().query(req_uri, null,
790 ProviderTableMeta.FILE_PARENT + "=?",
791 new String[]{String.valueOf(parentId)}, null);
792 } catch (RemoteException e) {
793 Log_OC.e(TAG, e.getMessage());
794 return ret;
795 }
796 } else {
797 c = getContentResolver().query(req_uri, null,
798 ProviderTableMeta.FILE_PARENT + "=?",
799 new String[]{String.valueOf(parentId)}, null);
800 }
801
802 if (c.moveToFirst()) {
803 do {
804 OCFile child = createFileInstance(c);
805 if (child.isFolder() || !onlyOnDevice || onlyOnDevice && child.isDown()){
806 ret.add(child);
807 }
808 } while (c.moveToNext());
809 }
810
811 c.close();
812
813 Collections.sort(ret);
814
815 return ret;
816 }
817
818
819 private OCFile createRootDir() {
820 OCFile file = new OCFile(OCFile.ROOT_PATH);
821 file.setMimetype("DIR");
822 file.setParentId(FileDataStorageManager.ROOT_PARENT_ID);
823 saveFile(file);
824 return file;
825 }
826
827 private boolean fileExists(String cmp_key, String value) {
828 Cursor c;
829 if (getContentResolver() != null) {
830 c = getContentResolver()
831 .query(ProviderTableMeta.CONTENT_URI,
832 null,
833 cmp_key + "=? AND "
834 + ProviderTableMeta.FILE_ACCOUNT_OWNER
835 + "=?",
836 new String[]{value, mAccount.name}, null);
837 } else {
838 try {
839 c = getContentProviderClient().query(
840 ProviderTableMeta.CONTENT_URI,
841 null,
842 cmp_key + "=? AND "
843 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
844 new String[]{value, mAccount.name}, null);
845 } catch (RemoteException e) {
846 Log_OC.e(TAG,
847 "Couldn't determine file existance, assuming non existance: "
848 + e.getMessage());
849 return false;
850 }
851 }
852 boolean retval = c.moveToFirst();
853 c.close();
854 return retval;
855 }
856
857 private Cursor getCursorForValue(String key, String value) {
858 Cursor c = null;
859 if (getContentResolver() != null) {
860 c = getContentResolver()
861 .query(ProviderTableMeta.CONTENT_URI,
862 null,
863 key + "=? AND "
864 + ProviderTableMeta.FILE_ACCOUNT_OWNER
865 + "=?",
866 new String[]{value, mAccount.name}, null);
867 } else {
868 try {
869 c = getContentProviderClient().query(
870 ProviderTableMeta.CONTENT_URI,
871 null,
872 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
873 + "=?", new String[]{value, mAccount.name},
874 null);
875 } catch (RemoteException e) {
876 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
877 c = null;
878 }
879 }
880 return c;
881 }
882
883
884 private OCFile createFileInstance(Cursor c) {
885 OCFile file = null;
886 if (c != null) {
887 file = new OCFile(c.getString(c
888 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
889 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
890 file.setParentId(c.getLong(c
891 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
892 file.setMimetype(c.getString(c
893 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
894 if (!file.isFolder()) {
895 file.setStoragePath(c.getString(c
896 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
897 if (file.getStoragePath() == null) {
898 // try to find existing file and bind it with current account;
899 // with the current update of SynchronizeFolderOperation, this won't be
900 // necessary anymore after a full synchronization of the account
901 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
902 if (f.exists()) {
903 file.setStoragePath(f.getAbsolutePath());
904 file.setLastSyncDateForData(f.lastModified());
905 }
906 }
907 }
908 file.setFileLength(c.getLong(c
909 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
910 file.setCreationTimestamp(c.getLong(c
911 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
912 file.setModificationTimestamp(c.getLong(c
913 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
914 file.setModificationTimestampAtLastSyncForData(c.getLong(c
915 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)));
916 file.setLastSyncDateForProperties(c.getLong(c
917 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
918 file.setLastSyncDateForData(c.getLong(c.
919 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
920 file.setFavorite(c.getInt(
921 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
922 file.setEtag(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)));
923 file.setShareViaLink(c.getInt(
924 c.getColumnIndex(ProviderTableMeta.FILE_SHARED_VIA_LINK)) == 1 ? true : false);
925 file.setShareWithSharee(c.getInt(
926 c.getColumnIndex(ProviderTableMeta.FILE_SHARED_WITH_SHAREE)) == 1 ? true : false);
927 file.setPublicLink(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PUBLIC_LINK)));
928 file.setPermissions(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PERMISSIONS)));
929 file.setRemoteId(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID)));
930 file.setNeedsUpdateThumbnail(c.getInt(
931 c.getColumnIndex(ProviderTableMeta.FILE_UPDATE_THUMBNAIL)) == 1 ? true : false);
932 file.setDownloading(c.getInt(
933 c.getColumnIndex(ProviderTableMeta.FILE_IS_DOWNLOADING)) == 1 ? true : false);
934 file.setEtagInConflict(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG_IN_CONFLICT)));
935
936 }
937 return file;
938 }
939
940 // Methods for Shares
941 public boolean saveShare(OCShare share) {
942 boolean overriden = false;
943 ContentValues cv = new ContentValues();
944 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
945 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
946 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
947 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
948 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
949 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
950 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
951 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
952 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
953 cv.put(
954 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
955 share.getSharedWithDisplayName()
956 );
957 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
958 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
959 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
960 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
961
962 if (shareExists(share.getIdRemoteShared())) {// for renamed files; no more delete and create
963 overriden = true;
964 if (getContentResolver() != null) {
965 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
966 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
967 new String[]{String.valueOf(share.getIdRemoteShared())});
968 } else {
969 try {
970 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
971 cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
972 new String[]{String.valueOf(share.getIdRemoteShared())});
973 } catch (RemoteException e) {
974 Log_OC.e(TAG,
975 "Fail to insert insert file to database "
976 + e.getMessage());
977 }
978 }
979 } else {
980 Uri result_uri = null;
981 if (getContentResolver() != null) {
982 result_uri = getContentResolver().insert(
983 ProviderTableMeta.CONTENT_URI_SHARE, cv);
984 } else {
985 try {
986 result_uri = getContentProviderClient().insert(
987 ProviderTableMeta.CONTENT_URI_SHARE, cv);
988 } catch (RemoteException e) {
989 Log_OC.e(TAG,
990 "Fail to insert insert file to database "
991 + e.getMessage());
992 }
993 }
994 if (result_uri != null) {
995 long new_id = Long.parseLong(result_uri.getPathSegments()
996 .get(1));
997 share.setId(new_id);
998 }
999 }
1000
1001 return overriden;
1002 }
1003
1004
1005 public OCShare getFirstShareByPathAndType(String path, ShareType type, String shareWith) {
1006 Cursor c = null;
1007
1008 String selection = ProviderTableMeta.OCSHARES_PATH + "=? AND "
1009 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
1010 + ProviderTableMeta.OCSHARES_SHARE_WITH + "=? AND "
1011 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" ;
1012
1013 String [] selectionArgs = new String[]{path, Integer.toString(type.getValue()),
1014 shareWith, mAccount.name};
1015
1016 if (getContentResolver() != null) {
1017 c = getContentResolver().query(
1018 ProviderTableMeta.CONTENT_URI_SHARE,
1019 null,
1020 selection, selectionArgs,
1021 null);
1022 } else {
1023 try {
1024 c = getContentProviderClient().query(
1025 ProviderTableMeta.CONTENT_URI_SHARE,
1026 null,
1027 selection, selectionArgs,
1028 null);
1029
1030 } catch (RemoteException e) {
1031 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
1032 c = null;
1033 }
1034 }
1035 OCShare share = null;
1036 if (c.moveToFirst()) {
1037 share = createShareInstance(c);
1038 }
1039 c.close();
1040 return share;
1041 }
1042
1043 private OCShare createShareInstance(Cursor c) {
1044 OCShare share = null;
1045 if (c != null) {
1046 share = new OCShare(c.getString(c
1047 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
1048 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1049 share.setFileSource(c.getLong(c
1050 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
1051 share.setShareType(ShareType.fromValue(c.getInt(c
1052 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
1053 share.setShareWith(c.getString(c
1054 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH)));
1055 share.setPermissions(c.getInt(c
1056 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
1057 share.setSharedDate(c.getLong(c
1058 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
1059 share.setExpirationDate(c.getLong(c
1060 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
1061 share.setToken(c.getString(c
1062 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
1063 share.setSharedWithDisplayName(c.getString(c
1064 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
1065 share.setIsFolder(c.getInt(
1066 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1);
1067 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
1068 share.setIdRemoteShared(c.getLong(
1069 c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED)));
1070 }
1071 return share;
1072 }
1073
1074 private boolean shareExists(String cmp_key, String value) {
1075 Cursor c;
1076 if (getContentResolver() != null) {
1077 c = getContentResolver()
1078 .query(ProviderTableMeta.CONTENT_URI_SHARE,
1079 null,
1080 cmp_key + "=? AND "
1081 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
1082 + "=?",
1083 new String[]{value, mAccount.name}, null);
1084 } else {
1085 try {
1086 c = getContentProviderClient().query(
1087 ProviderTableMeta.CONTENT_URI_SHARE,
1088 null,
1089 cmp_key + "=? AND "
1090 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1091 new String[]{value, mAccount.name}, null);
1092 } catch (RemoteException e) {
1093 Log_OC.e(TAG,
1094 "Couldn't determine file existance, assuming non existance: "
1095 + e.getMessage());
1096 return false;
1097 }
1098 }
1099 boolean retval = c.moveToFirst();
1100 c.close();
1101 return retval;
1102 }
1103
1104 private boolean shareExists(long remoteId) {
1105 return shareExists(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, String.valueOf(remoteId));
1106 }
1107
1108 private void resetShareFlagsInAllFiles() {
1109 ContentValues cv = new ContentValues();
1110 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false);
1111 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false);
1112 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1113 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
1114 String[] whereArgs = new String[]{mAccount.name};
1115
1116 if (getContentResolver() != null) {
1117 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1118
1119 } else {
1120 try {
1121 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where,
1122 whereArgs);
1123 } catch (RemoteException e) {
1124 Log_OC.e(TAG, "Exception in resetShareFlagsInAllFiles" + e.getMessage());
1125 }
1126 }
1127 }
1128
1129 private void resetShareFlagsInFolder(OCFile folder) {
1130 ContentValues cv = new ContentValues();
1131 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false);
1132 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false);
1133 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1134 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1135 ProviderTableMeta.FILE_PARENT + "=?";
1136 String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
1137
1138 if (getContentResolver() != null) {
1139 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1140
1141 } else {
1142 try {
1143 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where,
1144 whereArgs);
1145 } catch (RemoteException e) {
1146 Log_OC.e(TAG, "Exception in resetShareFlagsInFolder " + e.getMessage());
1147 }
1148 }
1149 }
1150
1151 private void resetShareFlagInAFile(String filePath){
1152 ContentValues cv = new ContentValues();
1153 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false);
1154 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false);
1155 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1156 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1157 ProviderTableMeta.FILE_PATH+ "=?";
1158 String [] whereArgs = new String[] { mAccount.name , filePath };
1159
1160 if (getContentResolver() != null) {
1161 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1162
1163 } else {
1164 try {
1165 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where,
1166 whereArgs);
1167 } catch (RemoteException e) {
1168 Log_OC.e(TAG, "Exception in resetShareFlagsInFolder " + e.getMessage());
1169 }
1170 }
1171 }
1172
1173 private void cleanShares() {
1174 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1175 String[] whereArgs = new String[]{mAccount.name};
1176
1177 if (getContentResolver() != null) {
1178 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1179
1180 } else {
1181 try {
1182 getContentProviderClient().delete(ProviderTableMeta.CONTENT_URI_SHARE, where,
1183 whereArgs);
1184 } catch (RemoteException e) {
1185 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
1186 }
1187 }
1188 }
1189
1190 public void saveShares(Collection<OCShare> shares) {
1191 cleanShares();
1192 if (shares != null) {
1193 ArrayList<ContentProviderOperation> operations =
1194 new ArrayList<ContentProviderOperation>(shares.size());
1195
1196 // prepare operations to insert or update files to save in the given folder
1197 for (OCShare share : shares) {
1198 ContentValues cv = new ContentValues();
1199 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1200 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1201 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1202 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1203 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1204 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1205 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1206 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1207 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1208 cv.put(
1209 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1210 share.getSharedWithDisplayName()
1211 );
1212 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1213 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1214 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1215 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1216
1217 if (shareExists(share.getIdRemoteShared())) {
1218 // updating an existing file
1219 operations.add(
1220 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1221 withValues(cv).
1222 withSelection(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1223 new String[]{String.valueOf(share.getIdRemoteShared())})
1224 .build());
1225 } else {
1226 // adding a new file
1227 operations.add(
1228 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1229 withValues(cv).
1230 build()
1231 );
1232 }
1233 }
1234
1235 // apply operations in batch
1236 if (operations.size() > 0) {
1237 @SuppressWarnings("unused")
1238 ContentProviderResult[] results = null;
1239 Log_OC.d(TAG, "Sending " + operations.size() +
1240 " operations to FileContentProvider");
1241 try {
1242 if (getContentResolver() != null) {
1243 results = getContentResolver().applyBatch(MainApp.getAuthority(),
1244 operations);
1245 } else {
1246 results = getContentProviderClient().applyBatch(operations);
1247 }
1248
1249 } catch (OperationApplicationException e) {
1250 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1251
1252 } catch (RemoteException e) {
1253 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1254 }
1255 }
1256 }
1257
1258 }
1259
1260 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1261 resetShareFlagsInAllFiles();
1262
1263 if (sharedFiles != null) {
1264 ArrayList<ContentProviderOperation> operations =
1265 new ArrayList<ContentProviderOperation>(sharedFiles.size());
1266
1267 // prepare operations to insert or update files to save in the given folder
1268 for (OCFile file : sharedFiles) {
1269 ContentValues cv = new ContentValues();
1270 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1271 cv.put(
1272 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
1273 file.getModificationTimestampAtLastSyncForData()
1274 );
1275 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1276 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1277 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1278 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1279 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1280 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1281 if (!file.isFolder()) {
1282 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1283 }
1284 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1285 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1286 cv.put(
1287 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
1288 file.getLastSyncDateForData()
1289 );
1290 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.isFavorite() ? 1 : 0);
1291 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1292 cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
1293 cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
1294 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1295 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
1296 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
1297 cv.put(
1298 ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
1299 file.needsUpdateThumbnail() ? 1 : 0
1300 );
1301 cv.put(
1302 ProviderTableMeta.FILE_IS_DOWNLOADING,
1303 file.isDownloading() ? 1 : 0
1304 );
1305 cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
1306
1307 boolean existsByPath = fileExists(file.getRemotePath());
1308 if (existsByPath || fileExists(file.getFileId())) {
1309 // updating an existing file
1310 operations.add(
1311 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1312 withValues(cv).
1313 withSelection(ProviderTableMeta._ID + "=?",
1314 new String[]{String.valueOf(file.getFileId())})
1315 .build());
1316
1317 } else {
1318 // adding a new file
1319 operations.add(
1320 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
1321 withValues(cv).
1322 build()
1323 );
1324 }
1325 }
1326
1327 // apply operations in batch
1328 if (operations.size() > 0) {
1329 @SuppressWarnings("unused")
1330 ContentProviderResult[] results = null;
1331 Log_OC.d(TAG, "Sending " + operations.size() +
1332 " operations to FileContentProvider");
1333 try {
1334 if (getContentResolver() != null) {
1335 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1336 } else {
1337 results = getContentProviderClient().applyBatch(operations);
1338 }
1339
1340 } catch (OperationApplicationException e) {
1341 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1342
1343 } catch (RemoteException e) {
1344 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1345 }
1346 }
1347 }
1348
1349 }
1350
1351 public void removeShare(OCShare share) {
1352 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1353 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
1354 ProviderTableMeta._ID + "=?";
1355 String [] whereArgs = new String[]{mAccount.name, Long.toString(share.getId())};
1356 if (getContentProviderClient() != null) {
1357 try {
1358 getContentProviderClient().delete(share_uri, where, whereArgs);
1359 } catch (RemoteException e) {
1360 e.printStackTrace();
1361 }
1362 } else {
1363 getContentResolver().delete(share_uri, where, whereArgs);
1364 }
1365 }
1366
1367 public void saveSharesDB(ArrayList<OCShare> shares) {
1368 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1369
1370 // Reset flags & Remove shares for this files
1371 String filePath = "";
1372 for (OCShare share: shares) {
1373 if (filePath != share.getPath()){
1374 filePath = share.getPath();
1375 resetShareFlagInAFile(filePath);
1376 operations = prepareRemoveSharesInFile(filePath, operations);
1377 }
1378 }
1379
1380 // Add operations to insert shares
1381 operations = prepareInsertShares(shares, operations);
1382
1383 // apply operations in batch
1384 if (operations.size() > 0) {
1385 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1386 try {
1387 if (getContentResolver() != null) {
1388 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1389
1390 } else {
1391 getContentProviderClient().applyBatch(operations);
1392 }
1393
1394 } catch (OperationApplicationException e) {
1395 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1396
1397 } catch (RemoteException e) {
1398 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1399 }
1400 }
1401
1402 // // TODO: review if it is needed
1403 // // Update shared files
1404 // ArrayList<OCFile> sharedFiles = new ArrayList<OCFile>();
1405 //
1406 // for (OCShare share : shares) {
1407 // // Get the path
1408 // String path = share.getPath();
1409 // if (share.isFolder()) {
1410 // path = path + FileUtils.PATH_SEPARATOR;
1411 // }
1412 //
1413 // // Update OCFile with data from share: ShareByLink, publicLink and
1414 // OCFile file = getFileByPath(path);
1415 // if (file != null) {
1416 // if (share.getShareType().equals(ShareType.PUBLIC_LINK)) {
1417 // file.setShareViaLink(true);
1418 // sharedFiles.add(file);
1419 // }
1420 // }
1421 // }
1422 //
1423 // // TODO: Review
1424 // updateSharedFiles(sharedFiles);
1425 }
1426
1427
1428 public void saveSharesInFolder(ArrayList<OCShare> shares, OCFile folder) {
1429 resetShareFlagsInFolder(folder);
1430 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1431 operations = prepareRemoveSharesInFolder(folder, operations);
1432
1433 if (shares != null) {
1434 // prepare operations to insert or update files to save in the given folder
1435 operations = prepareInsertShares(shares, operations);
1436 }
1437
1438 // apply operations in batch
1439 if (operations.size() > 0) {
1440 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1441 try {
1442 if (getContentResolver() != null) {
1443 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1444
1445 } else {
1446 getContentProviderClient().applyBatch(operations);
1447 }
1448
1449 } catch (OperationApplicationException e) {
1450 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1451
1452 } catch (RemoteException e) {
1453
1454 }
1455 }
1456
1457 }
1458
1459 /**
1460 * Prepare operations to insert or update files to save in the given folder
1461 * @param shares List of shares to insert
1462 * @param operations List of operations
1463 * @return
1464 */
1465 private ArrayList<ContentProviderOperation> prepareInsertShares(
1466 ArrayList<OCShare> shares, ArrayList<ContentProviderOperation> operations) {
1467
1468 if (shares != null) {
1469 // prepare operations to insert or update files to save in the given folder
1470 for (OCShare share : shares) {
1471 ContentValues cv = new ContentValues();
1472 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1473 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1474 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1475 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1476 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1477 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1478 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1479 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1480 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1481 cv.put(
1482 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1483 share.getSharedWithDisplayName()
1484 );
1485 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1486 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1487 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1488 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1489
1490 // adding a new share resource
1491 operations.add(
1492 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1493 withValues(cv).
1494 build()
1495 );
1496 }
1497 }
1498 return operations;
1499 }
1500
1501 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
1502 OCFile folder, ArrayList<ContentProviderOperation> preparedOperations) {
1503 if (folder != null) {
1504 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1505 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1506 String [] whereArgs = new String[]{ "", mAccount.name };
1507
1508 Vector<OCFile> files = getFolderContent(folder, false);
1509
1510 for (OCFile file : files) {
1511 whereArgs[0] = file.getRemotePath();
1512 preparedOperations.add(
1513 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1514 withSelection(where, whereArgs).
1515 build()
1516 );
1517 }
1518 }
1519 return preparedOperations;
1520
1521 }
1522
1523 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFile(
1524 String filePath, ArrayList<ContentProviderOperation> preparedOperations) {
1525
1526 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1527 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1528 String[] whereArgs = new String[]{filePath, mAccount.name};
1529
1530 preparedOperations.add(
1531 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1532 withSelection(where, whereArgs).
1533 build()
1534 );
1535
1536 return preparedOperations;
1537
1538 }
1539
1540 public ArrayList<OCShare> getSharesWithForAFile(String filePath, String accountName){
1541 // Condition
1542 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1543 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"+ "AND"
1544 + " (" + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR "
1545 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? ) ";
1546 String [] whereArgs = new String[]{ filePath, accountName ,
1547 Integer.toString(ShareType.USER.getValue()),
1548 Integer.toString(ShareType.GROUP.getValue()) };
1549
1550 Cursor c = null;
1551 if (getContentResolver() != null) {
1552 c = getContentResolver().query(
1553 ProviderTableMeta.CONTENT_URI_SHARE,
1554 null, where, whereArgs, null);
1555 } else {
1556 try {
1557 c = getContentProviderClient().query(
1558 ProviderTableMeta.CONTENT_URI_SHARE,
1559 null, where, whereArgs, null);
1560
1561 } catch (RemoteException e) {
1562 Log_OC.e(TAG, "Could not get list of shares with: " + e.getMessage());
1563 c = null;
1564 }
1565 }
1566 ArrayList<OCShare> shares = new ArrayList<OCShare>();
1567 OCShare share = null;
1568 if (c.moveToFirst()) {
1569 do {
1570 share = createShareInstance(c);
1571 shares.add(share);
1572 // }
1573 } while (c.moveToNext());
1574 }
1575 c.close();
1576
1577 return shares;
1578 }
1579
1580 public static void triggerMediaScan(String path) {
1581 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1582 intent.setData(Uri.fromFile(new File(path)));
1583 MainApp.getAppContext().sendBroadcast(intent);
1584 }
1585
1586 public void deleteFileInMediaScan(String path) {
1587
1588 String mimetypeString = FileStorageUtils.getMimeTypeFromName(path);
1589 ContentResolver contentResolver = getContentResolver();
1590
1591 if (contentResolver != null) {
1592 if (mimetypeString.startsWith("image/")) {
1593 // Images
1594 contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1595 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1596 } else if (mimetypeString.startsWith("audio/")) {
1597 // Audio
1598 contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1599 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1600 } else if (mimetypeString.startsWith("video/")) {
1601 // Video
1602 contentResolver.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1603 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1604 }
1605 } else {
1606 ContentProviderClient contentProviderClient = getContentProviderClient();
1607 try {
1608 if (mimetypeString.startsWith("image/")) {
1609 // Images
1610 contentProviderClient.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1611 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1612 } else if (mimetypeString.startsWith("audio/")) {
1613 // Audio
1614 contentProviderClient.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1615 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1616 } else if (mimetypeString.startsWith("video/")) {
1617 // Video
1618 contentProviderClient.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1619 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1620 }
1621 } catch (RemoteException e) {
1622 Log_OC.e(TAG, "Exception deleting media file in MediaStore " + e.getMessage());
1623 }
1624 }
1625
1626 }
1627
1628 public void saveConflict(OCFile file, String etagInConflict) {
1629 if (!file.isDown()) {
1630 etagInConflict = null;
1631 }
1632 ContentValues cv = new ContentValues();
1633 cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, etagInConflict);
1634 int updated = 0;
1635 if (getContentResolver() != null) {
1636 updated = getContentResolver().update(
1637 ProviderTableMeta.CONTENT_URI_FILE,
1638 cv,
1639 ProviderTableMeta._ID + "=?",
1640 new String[] { String.valueOf(file.getFileId())}
1641 );
1642 } else {
1643 try {
1644 updated = getContentProviderClient().update(
1645 ProviderTableMeta.CONTENT_URI_FILE,
1646 cv,
1647 ProviderTableMeta._ID + "=?",
1648 new String[]{String.valueOf(file.getFileId())}
1649 );
1650 } catch (RemoteException e) {
1651 Log_OC.e(TAG, "Failed saving conflict in database " + e.getMessage());
1652 }
1653 }
1654
1655 Log_OC.d(TAG, "Number of files updated with CONFLICT: " + updated);
1656
1657 if (updated > 0) {
1658 if (etagInConflict != null) {
1659 /// set conflict in all ancestor folders
1660
1661 long parentId = file.getParentId();
1662 Set<String> ancestorIds = new HashSet<String>();
1663 while (parentId != FileDataStorageManager.ROOT_PARENT_ID) {
1664 ancestorIds.add(Long.toString(parentId));
1665 parentId = getFileById(parentId).getParentId();
1666 }
1667
1668 if (ancestorIds.size() > 0) {
1669 StringBuffer whereBuffer = new StringBuffer();
1670 whereBuffer.append(ProviderTableMeta._ID).append(" IN (");
1671 for (int i = 0; i < ancestorIds.size() - 1; i++) {
1672 whereBuffer.append("?,");
1673 }
1674 whereBuffer.append("?");
1675 whereBuffer.append(")");
1676
1677 if (getContentResolver() != null) {
1678 updated = getContentResolver().update(
1679 ProviderTableMeta.CONTENT_URI_FILE,
1680 cv,
1681 whereBuffer.toString(),
1682 ancestorIds.toArray(new String[]{})
1683 );
1684 } else {
1685 try {
1686 updated = getContentProviderClient().update(
1687 ProviderTableMeta.CONTENT_URI_FILE,
1688 cv,
1689 whereBuffer.toString(),
1690 ancestorIds.toArray(new String[]{})
1691 );
1692 } catch (RemoteException e) {
1693 Log_OC.e(TAG, "Failed saving conflict in database " + e.getMessage());
1694 }
1695 }
1696 } // else file is ROOT folder, no parent to set in conflict
1697
1698 } else {
1699 /// update conflict in ancestor folders
1700 // (not directly unset; maybe there are more conflicts below them)
1701 String parentPath = file.getRemotePath();
1702 if (parentPath.endsWith(OCFile.PATH_SEPARATOR)) {
1703 parentPath = parentPath.substring(0, parentPath.length() - 1);
1704 }
1705 parentPath = parentPath.substring(0, parentPath.lastIndexOf(OCFile.PATH_SEPARATOR) + 1);
1706
1707 Log_OC.d(TAG, "checking parents to remove conflict; STARTING with " + parentPath);
1708 while (parentPath.length() > 0) {
1709
1710 String where =
1711 ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " IS NOT NULL AND " +
1712 ProviderTableMeta.FILE_CONTENT_TYPE + " != 'DIR' AND " +
1713 ProviderTableMeta.FILE_ACCOUNT_OWNER + " = ? AND " +
1714 ProviderTableMeta.FILE_PATH + " LIKE ?";
1715 Cursor descendentsInConflict = getContentResolver().query(
1716 ProviderTableMeta.CONTENT_URI_FILE,
1717 new String[]{ProviderTableMeta._ID},
1718 where,
1719 new String[]{mAccount.name, parentPath + "%"},
1720 null
1721 );
1722 if (descendentsInConflict == null || descendentsInConflict.getCount() == 0) {
1723 Log_OC.d(TAG, "NO MORE conflicts in " + parentPath);
1724 if (getContentResolver() != null) {
1725 updated = getContentResolver().update(
1726 ProviderTableMeta.CONTENT_URI_FILE,
1727 cv,
1728 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1729 ProviderTableMeta.FILE_PATH + "=?",
1730 new String[]{mAccount.name, parentPath}
1731 );
1732 } else {
1733 try {
1734 updated = getContentProviderClient().update(
1735 ProviderTableMeta.CONTENT_URI_FILE,
1736 cv,
1737 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1738 ProviderTableMeta.FILE_PATH + "=?"
1739 , new String[]{mAccount.name, parentPath}
1740 );
1741 } catch (RemoteException e) {
1742 Log_OC.e(TAG, "Failed saving conflict in database " + e.getMessage());
1743 }
1744 }
1745
1746 } else {
1747 Log_OC.d(TAG, "STILL " + descendentsInConflict.getCount() + " in " + parentPath);
1748 }
1749
1750 if (descendentsInConflict != null) {
1751 descendentsInConflict.close();
1752 }
1753
1754 parentPath = parentPath.substring(0, parentPath.length() - 1); // trim last /
1755 parentPath = parentPath.substring(0, parentPath.lastIndexOf(OCFile.PATH_SEPARATOR) + 1);
1756 Log_OC.d(TAG, "checking parents to remove conflict; NEXT " + parentPath);
1757 }
1758 }
1759 }
1760
1761 }
1762
1763 public OCCapability saveCapabilities(OCCapability capability){
1764
1765 // Prepare capabilities data
1766 ContentValues cv = new ContentValues();
1767 cv.put(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME, mAccount.name);
1768 cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR, capability.getVersionMayor());
1769 cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MINOR, capability.getVersionMinor());
1770 cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MICRO, capability.getVersionMicro());
1771 cv.put(ProviderTableMeta.CAPABILITIES_VERSION_STRING, capability.getVersionString());
1772 cv.put(ProviderTableMeta.CAPABILITIES_VERSION_EDITION, capability.getVersionEdition());
1773 cv.put(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL, capability.getCorePollinterval());
1774 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED, capability.getFilesSharingApiEnabled().getValue());
1775 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED,
1776 capability.getFilesSharingPublicEnabled().getValue());
1777 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED,
1778 capability.getFilesSharingPublicPasswordEnforced().getValue());
1779 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED,
1780 capability.getFilesSharingPublicExpireDateEnabled().getValue());
1781 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS,
1782 capability.getFilesSharingPublicExpireDateDays());
1783 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED,
1784 capability.getFilesSharingPublicExpireDateEnforced().getValue());
1785 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL,
1786 capability.getFilesSharingPublicSendMail().getValue());
1787 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD,
1788 capability.getFilesSharingPublicUpload().getValue());
1789 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL,
1790 capability.getFilesSharingUserSendMail().getValue());
1791 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING, capability.getFilesSharingResharing().getValue());
1792 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING,
1793 capability.getFilesSharingFederationOutgoing().getValue());
1794 cv.put(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING,
1795 capability.getFilesSharingFederationIncoming().getValue());
1796 cv.put(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING, capability.getFilesBigFileChuncking().getValue());
1797 cv.put(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE, capability.getFilesUndelete().getValue());
1798 cv.put(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING, capability.getFilesVersioning().getValue());
1799
1800 if (capabilityExists(mAccount.name)) {
1801 if (getContentResolver() != null) {
1802 getContentResolver().update(ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv,
1803 ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=?",
1804 new String[]{mAccount.name});
1805 } else {
1806 try {
1807 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_CAPABILITIES,
1808 cv, ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=?",
1809 new String[]{mAccount.name});
1810 } catch (RemoteException e) {
1811 Log_OC.e(TAG,
1812 "Fail to insert insert file to database "
1813 + e.getMessage());
1814 }
1815 }
1816 } else {
1817 Uri result_uri = null;
1818 if (getContentResolver() != null) {
1819 result_uri = getContentResolver().insert(
1820 ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv);
1821 } else {
1822 try {
1823 result_uri = getContentProviderClient().insert(
1824 ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv);
1825 } catch (RemoteException e) {
1826 Log_OC.e(TAG,
1827 "Fail to insert insert capability to database "
1828 + e.getMessage());
1829 }
1830 }
1831 if (result_uri != null) {
1832 long new_id = Long.parseLong(result_uri.getPathSegments()
1833 .get(1));
1834 capability.setId(new_id);
1835 capability.setAccountName(mAccount.name);
1836 }
1837 }
1838
1839 return capability;
1840 }
1841
1842 private boolean capabilityExists(String accountName) {
1843 Cursor c = getCapabilityCursorForAccount(accountName);
1844 boolean exists = false;
1845 if (c != null) {
1846 exists = c.moveToFirst();
1847 c.close();
1848 }
1849 return exists;
1850 }
1851
1852 private Cursor getCapabilityCursorForAccount(String accountName){
1853 Cursor c = null;
1854 if (getContentResolver() != null) {
1855 c = getContentResolver()
1856 .query(ProviderTableMeta.CONTENT_URI_CAPABILITIES,
1857 null,
1858 ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=? ",
1859 new String[]{accountName}, null);
1860 } else {
1861 try {
1862 c = getContentProviderClient().query(
1863 ProviderTableMeta.CONTENT_URI_CAPABILITIES,
1864 null,
1865 ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=? ",
1866 new String[]{accountName}, null);
1867 } catch (RemoteException e) {
1868 Log_OC.e(TAG,
1869 "Couldn't determine capability existance, assuming non existance: "
1870 + e.getMessage());
1871 }
1872 }
1873
1874 return c;
1875
1876 }
1877 public OCCapability getCapability(String accountName){
1878 OCCapability capability = null;
1879 Cursor c = getCapabilityCursorForAccount(accountName);
1880
1881 if (c.moveToFirst()) {
1882 capability = createCapabilityInstance(c);
1883 }
1884 c.close();
1885 return capability;
1886 }
1887
1888 private OCCapability createCapabilityInstance(Cursor c) {
1889 OCCapability capability = null;
1890 if (c != null) {
1891 capability = new OCCapability();
1892 capability.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1893 capability.setAccountName(c.getString(c
1894 .getColumnIndex(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME)));
1895 capability.setVersionMayor(c.getInt(c
1896 .getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR)));
1897 capability.setVersionMinor(c.getInt(c
1898 .getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MINOR)));
1899 capability.setVersionMicro(c.getInt(c
1900 .getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MICRO)));
1901 capability.setVersionString(c.getString(c
1902 .getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_STRING)));
1903 capability.setVersionEdition(c.getString(c
1904 .getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_EDITION)));
1905 capability.setCorePollinterval(c.getInt(c
1906 .getColumnIndex(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL)));
1907 capability.setFilesSharingApiEnabled(CapabilityBooleanType.fromValue(c.getInt(c
1908 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED))));
1909 capability.setFilesSharingPublicEnabled(CapabilityBooleanType.fromValue(c.getInt(c
1910 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED))));
1911 capability.setFilesSharingPublicPasswordEnforced(CapabilityBooleanType.fromValue(c.getInt(c
1912 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED))));
1913 capability.setFilesSharingPublicExpireDateEnabled(CapabilityBooleanType.fromValue(c.getInt(c
1914 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED))));
1915 capability.setFilesSharingPublicExpireDateDays(c.getInt(c
1916 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS)));
1917 capability.setFilesSharingPublicExpireDateEnforced(CapabilityBooleanType.fromValue(c.getInt(c
1918 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED))));
1919 capability.setFilesSharingPublicSendMail(CapabilityBooleanType.fromValue(c.getInt(c
1920 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL))));
1921 capability.setFilesSharingPublicUpload(CapabilityBooleanType.fromValue(c.getInt(c
1922 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD))));
1923 capability.setFilesSharingUserSendMail(CapabilityBooleanType.fromValue(c.getInt(c
1924 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL))));
1925 capability.setFilesSharingResharing(CapabilityBooleanType.fromValue(c.getInt(c
1926 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING))));
1927 capability.setFilesSharingFederationOutgoing(CapabilityBooleanType.fromValue(c.getInt(c
1928 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING))));
1929 capability.setFilesSharingFederationIncoming(CapabilityBooleanType.fromValue(c.getInt(c
1930 .getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING))));
1931 capability.setFilesBigFileChuncking(CapabilityBooleanType.fromValue(c.getInt(c
1932 .getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING))));
1933 capability.setFilesUndelete(CapabilityBooleanType.fromValue(c.getInt(c
1934 .getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE))));
1935 capability.setFilesVersioning(CapabilityBooleanType.fromValue(c.getInt(c
1936 .getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING))));
1937
1938 }
1939 return capability;
1940 }
1941 }