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