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