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