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