Refactoring: move all the intents for MediaScanner in FileDataStorageManager to a...
[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 if (removeLocalCopy && file.isDown() && file.getStoragePath() != null && success) {
490 success = new File(file.getStoragePath()).delete();
491 if (!removeDBData && success) {
492 // maybe unnecessary, but should be checked TODO remove if unnecessary
493 file.setStoragePath(null);
494 saveFile(file);
495 }
496 }
497 }
498 }
499 return success;
500 }
501
502
503 public boolean removeFolder(OCFile folder, boolean removeDBData, boolean removeLocalContent) {
504 boolean success = true;
505 if (folder != null && folder.isFolder()) {
506 if (removeDBData && folder.getFileId() != -1) {
507 success = removeFolderInDb(folder);
508 }
509 if (removeLocalContent && success) {
510 success = removeLocalFolder(folder);
511 }
512 }
513 return success;
514 }
515
516 private boolean removeFolderInDb(OCFile folder) {
517 Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" +
518 folder.getFileId()); // URI for recursive deletion
519 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
520 ProviderTableMeta.FILE_PATH + "=?";
521 String [] whereArgs = new String[]{mAccount.name, folder.getRemotePath()};
522 int deleted = 0;
523 if (getContentProviderClient() != null) {
524 try {
525 deleted = getContentProviderClient().delete(folder_uri, where, whereArgs);
526 } catch (RemoteException e) {
527 e.printStackTrace();
528 }
529 } else {
530 deleted = getContentResolver().delete(folder_uri, where, whereArgs);
531 }
532 return deleted > 0;
533 }
534
535 private boolean removeLocalFolder(OCFile folder) {
536 boolean success = true;
537 File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, folder));
538 if (localFolder.exists()) {
539 // stage 1: remove the local files already registered in the files database
540 Vector<OCFile> files = getFolderContent(folder.getFileId());
541 if (files != null) {
542 for (OCFile file : files) {
543 if (file.isFolder()) {
544 success &= removeLocalFolder(file);
545 } else {
546 if (file.isDown()) {
547 String path = file.getStoragePath();
548 File localFile = new File(file.getStoragePath());
549 success &= localFile.delete();
550 if (success) {
551 file.setStoragePath(null);
552 saveFile(file);
553 triggerMediaScan(path); // notify MediaScanner about removed file
554 }
555 }
556 }
557 }
558 }
559
560 // stage 2: remove the folder itself and any local file inside out of sync;
561 // for instance, after clearing the app cache or reinstalling
562 success &= removeLocalFolder(localFolder);
563 }
564 return success;
565 }
566
567 private boolean removeLocalFolder(File localFolder) {
568 boolean success = true;
569 File[] localFiles = localFolder.listFiles();
570 if (localFiles != null) {
571 for (File localFile : localFiles) {
572 if (localFile.isDirectory()) {
573 success &= removeLocalFolder(localFile);
574 } else {
575 String path = localFile.getAbsolutePath();
576 success &= localFile.delete();
577 triggerMediaScan(path); // notify MediaScanner about removed file
578 }
579 }
580 }
581 success &= localFolder.delete();
582 return success;
583 }
584
585 /**
586 * Updates database for a folder that was moved to a different location.
587 *
588 * TODO explore better (faster) implementations
589 * TODO throw exceptions up !
590 */
591 public void moveFolder(OCFile folder, String newPath) {
592 // TODO check newPath
593
594 if ( folder != null && folder.isFolder() &&
595 folder.fileExists() && !OCFile.ROOT_PATH.equals(folder.getFileName())
596 ) {
597 /// 1. get all the descendants of 'dir' in a single QUERY (including 'dir')
598 Cursor c = null;
599 if (getContentProviderClient() != null) {
600 try {
601 c = getContentProviderClient().query (
602 ProviderTableMeta.CONTENT_URI,
603 null,
604 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
605 ProviderTableMeta.FILE_PATH + " LIKE ? ",
606 new String[] { mAccount.name, folder.getRemotePath() + "%" },
607 ProviderTableMeta.FILE_PATH + " ASC "
608 );
609 } catch (RemoteException e) {
610 Log_OC.e(TAG, e.getMessage());
611 }
612 } else {
613 c = getContentResolver().query (
614 ProviderTableMeta.CONTENT_URI,
615 null,
616 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
617 ProviderTableMeta.FILE_PATH + " LIKE ? ",
618 new String[] { mAccount.name, folder.getRemotePath() + "%" },
619 ProviderTableMeta.FILE_PATH + " ASC "
620 );
621 }
622
623 /// 2. prepare a batch of update operations to change all the descendants
624 ArrayList<ContentProviderOperation> operations =
625 new ArrayList<ContentProviderOperation>(c.getCount());
626 int lengthOfOldPath = folder.getRemotePath().length();
627 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
628 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
629 if (c.moveToFirst()) {
630 do {
631 ContentValues cv = new ContentValues(); // keep the constructor in the loop
632 OCFile child = createFileInstance(c);
633 cv.put(
634 ProviderTableMeta.FILE_PATH,
635 newPath + child.getRemotePath().substring(lengthOfOldPath)
636 );
637 if ( child.getStoragePath() != null &&
638 child.getStoragePath().startsWith(defaultSavePath) ) {
639 cv.put(
640 ProviderTableMeta.FILE_STORAGE_PATH,
641 defaultSavePath + newPath +
642 child.getStoragePath().substring(lengthOfOldStoragePath)
643 );
644 }
645 operations.add(
646 ContentProviderOperation.
647 newUpdate(ProviderTableMeta.CONTENT_URI).
648 withValues(cv).
649 withSelection(
650 ProviderTableMeta._ID + "=?",
651 new String[] { String.valueOf(child.getFileId()) }
652 ).
653 build()
654 );
655 } while (c.moveToNext());
656 }
657 c.close();
658
659 /// 3. apply updates in batch
660 try {
661 if (getContentResolver() != null) {
662 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
663
664 } else {
665 getContentProviderClient().applyBatch(operations);
666 }
667
668 } catch (OperationApplicationException e) {
669 Log_OC.e(TAG, "Fail to update descendants of " +
670 folder.getFileId() + " in database", e);
671
672 } catch (RemoteException e) {
673 Log_OC.e(TAG, "Fail to update desendants of " +
674 folder.getFileId() + " in database", e);
675 }
676
677 }
678 }
679
680
681 public void moveLocalFile(OCFile file, String targetPath, String targetParentPath) {
682
683 if (file != null && file.fileExists() && !OCFile.ROOT_PATH.equals(file.getFileName())) {
684
685 OCFile targetParent = getFileByPath(targetParentPath);
686 if (targetParent == null) {
687 // TODO panic
688 }
689
690 /// 1. get all the descendants of the moved element in a single QUERY
691 Cursor c = null;
692 if (getContentProviderClient() != null) {
693 try {
694 c = getContentProviderClient().query(
695 ProviderTableMeta.CONTENT_URI,
696 null,
697 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
698 ProviderTableMeta.FILE_PATH + " LIKE ? ",
699 new String[] {
700 mAccount.name,
701 file.getRemotePath() + "%"
702 },
703 ProviderTableMeta.FILE_PATH + " ASC "
704 );
705 } catch (RemoteException e) {
706 Log_OC.e(TAG, e.getMessage());
707 }
708
709 } else {
710 c = getContentResolver().query(
711 ProviderTableMeta.CONTENT_URI,
712 null,
713 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
714 ProviderTableMeta.FILE_PATH + " LIKE ? ",
715 new String[] {
716 mAccount.name,
717 file.getRemotePath() + "%"
718 },
719 ProviderTableMeta.FILE_PATH + " ASC "
720 );
721 }
722
723 /// 2. prepare a batch of update operations to change all the descendants
724 ArrayList<ContentProviderOperation> operations =
725 new ArrayList<ContentProviderOperation>(c.getCount());
726 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
727 if (c.moveToFirst()) {
728 int lengthOfOldPath = file.getRemotePath().length();
729 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
730 do {
731 ContentValues cv = new ContentValues(); // keep construction in the loop
732 OCFile child = createFileInstance(c);
733 cv.put(
734 ProviderTableMeta.FILE_PATH,
735 targetPath + child.getRemotePath().substring(lengthOfOldPath)
736 );
737 if (child.getStoragePath() != null &&
738 child.getStoragePath().startsWith(defaultSavePath)) {
739 // update link to downloaded content - but local move is not done here!
740 cv.put(
741 ProviderTableMeta.FILE_STORAGE_PATH,
742 defaultSavePath + targetPath +
743 child.getStoragePath().substring(lengthOfOldStoragePath)
744 );
745 }
746 if (child.getRemotePath().equals(file.getRemotePath())) {
747 cv.put(
748 ProviderTableMeta.FILE_PARENT,
749 targetParent.getFileId()
750 );
751 }
752 operations.add(
753 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
754 withValues(cv).
755 withSelection(
756 ProviderTableMeta._ID + "=?",
757 new String[] { String.valueOf(child.getFileId()) }
758 )
759 .build());
760
761 } while (c.moveToNext());
762 }
763 c.close();
764
765 /// 3. apply updates in batch
766 try {
767 if (getContentResolver() != null) {
768 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
769
770 } else {
771 getContentProviderClient().applyBatch(operations);
772 }
773
774 } catch (Exception e) {
775 Log_OC.e(
776 TAG,
777 "Fail to update " + file.getFileId() + " and descendants in database",
778 e
779 );
780 }
781
782 /// 4. move in local file system
783 String localPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
784 File localFile = new File(localPath);
785 boolean renamed = false;
786 if (localFile.exists()) {
787 File targetFile = new File(defaultSavePath + targetPath);
788 File targetFolder = targetFile.getParentFile();
789 if (!targetFolder.exists()) {
790 targetFolder.mkdirs();
791 }
792 renamed = localFile.renameTo(targetFile);
793 }
794 Log_OC.d(TAG, "Local file RENAMED : " + renamed);
795
796 // Notify MediaScanner about removed file
797 triggerMediaScan(file.getStoragePath());
798
799 // Notify MediaScanner about new file/folder
800 triggerMediaScan(defaultSavePath + targetPath);
801
802 Log_OC.d(TAG, "uri old: " + file.getStoragePath());
803 Log_OC.d(TAG, "uri new: " + defaultSavePath + targetPath);
804 }
805
806 }
807
808
809 private Vector<OCFile> getFolderContent(long parentId) {
810
811 Vector<OCFile> ret = new Vector<OCFile>();
812
813 Uri req_uri = Uri.withAppendedPath(
814 ProviderTableMeta.CONTENT_URI_DIR,
815 String.valueOf(parentId));
816 Cursor c = null;
817
818 if (getContentProviderClient() != null) {
819 try {
820 c = getContentProviderClient().query(req_uri, null,
821 ProviderTableMeta.FILE_PARENT + "=?" ,
822 new String[] { String.valueOf(parentId)}, null);
823 } catch (RemoteException e) {
824 Log_OC.e(TAG, e.getMessage());
825 return ret;
826 }
827 } else {
828 c = getContentResolver().query(req_uri, null,
829 ProviderTableMeta.FILE_PARENT + "=?" ,
830 new String[] { String.valueOf(parentId)}, null);
831 }
832
833 if (c.moveToFirst()) {
834 do {
835 OCFile child = createFileInstance(c);
836 ret.add(child);
837 } while (c.moveToNext());
838 }
839
840 c.close();
841
842 Collections.sort(ret);
843
844 return ret;
845 }
846
847
848 private OCFile createRootDir() {
849 OCFile file = new OCFile(OCFile.ROOT_PATH);
850 file.setMimetype("DIR");
851 file.setParentId(FileDataStorageManager.ROOT_PARENT_ID);
852 saveFile(file);
853 return file;
854 }
855
856 private boolean fileExists(String cmp_key, String value) {
857 Cursor c;
858 if (getContentResolver() != null) {
859 c = getContentResolver()
860 .query(ProviderTableMeta.CONTENT_URI,
861 null,
862 cmp_key + "=? AND "
863 + ProviderTableMeta.FILE_ACCOUNT_OWNER
864 + "=?",
865 new String[] { value, mAccount.name }, null);
866 } else {
867 try {
868 c = getContentProviderClient().query(
869 ProviderTableMeta.CONTENT_URI,
870 null,
871 cmp_key + "=? AND "
872 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
873 new String[] { value, mAccount.name }, null);
874 } catch (RemoteException e) {
875 Log_OC.e(TAG,
876 "Couldn't determine file existance, assuming non existance: "
877 + e.getMessage());
878 return false;
879 }
880 }
881 boolean retval = c.moveToFirst();
882 c.close();
883 return retval;
884 }
885
886 private Cursor getCursorForValue(String key, String value) {
887 Cursor c = null;
888 if (getContentResolver() != null) {
889 c = getContentResolver()
890 .query(ProviderTableMeta.CONTENT_URI,
891 null,
892 key + "=? AND "
893 + ProviderTableMeta.FILE_ACCOUNT_OWNER
894 + "=?",
895 new String[] { value, mAccount.name }, null);
896 } else {
897 try {
898 c = getContentProviderClient().query(
899 ProviderTableMeta.CONTENT_URI,
900 null,
901 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
902 + "=?", new String[] { value, mAccount.name },
903 null);
904 } catch (RemoteException e) {
905 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
906 c = null;
907 }
908 }
909 return c;
910 }
911
912
913 private OCFile createFileInstance(Cursor c) {
914 OCFile file = null;
915 if (c != null) {
916 file = new OCFile(c.getString(c
917 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
918 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
919 file.setParentId(c.getLong(c
920 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
921 file.setMimetype(c.getString(c
922 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
923 if (!file.isFolder()) {
924 file.setStoragePath(c.getString(c
925 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
926 if (file.getStoragePath() == null) {
927 // try to find existing file and bind it with current account;
928 // with the current update of SynchronizeFolderOperation, this won't be
929 // necessary anymore after a full synchronization of the account
930 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
931 if (f.exists()) {
932 file.setStoragePath(f.getAbsolutePath());
933 file.setLastSyncDateForData(f.lastModified());
934 }
935 }
936 }
937 file.setFileLength(c.getLong(c
938 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
939 file.setCreationTimestamp(c.getLong(c
940 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
941 file.setModificationTimestamp(c.getLong(c
942 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
943 file.setModificationTimestampAtLastSyncForData(c.getLong(c
944 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)));
945 file.setLastSyncDateForProperties(c.getLong(c
946 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
947 file.setLastSyncDateForData(c.getLong(c.
948 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
949 file.setKeepInSync(c.getInt(
950 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
951 file.setEtag(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)));
952 file.setShareByLink(c.getInt(
953 c.getColumnIndex(ProviderTableMeta.FILE_SHARE_BY_LINK)) == 1 ? true : false);
954 file.setPublicLink(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PUBLIC_LINK)));
955 file.setPermissions(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PERMISSIONS)));
956 file.setRemoteId(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID)));
957 file.setNeedsUpdateThumbnail(c.getInt(
958 c.getColumnIndex(ProviderTableMeta.FILE_UPDATE_THUMBNAIL)) == 1 ? true : false);
959
960 }
961 return file;
962 }
963
964 /**
965 * Returns if the file/folder is shared by link or not
966 * @param path Path of the file/folder
967 * @return
968 */
969 public boolean isShareByLink(String path) {
970 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
971 OCFile file = null;
972 if (c.moveToFirst()) {
973 file = createFileInstance(c);
974 }
975 c.close();
976 return file.isShareByLink();
977 }
978
979 /**
980 * Returns the public link of the file/folder
981 * @param path Path of the file/folder
982 * @return
983 */
984 public String getPublicLink(String path) {
985 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
986 OCFile file = null;
987 if (c.moveToFirst()) {
988 file = createFileInstance(c);
989 }
990 c.close();
991 return file.getPublicLink();
992 }
993
994
995 // Methods for Shares
996 public boolean saveShare(OCShare share) {
997 boolean overriden = false;
998 ContentValues cv = new ContentValues();
999 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1000 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1001 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1002 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1003 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1004 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1005 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1006 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1007 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1008 cv.put(
1009 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1010 share.getSharedWithDisplayName()
1011 );
1012 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1013 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1014 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1015 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1016
1017 if (shareExists(share.getIdRemoteShared())) { // for renamed files
1018
1019 overriden = true;
1020 if (getContentResolver() != null) {
1021 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
1022 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1023 new String[] { String.valueOf(share.getIdRemoteShared()) });
1024 } else {
1025 try {
1026 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
1027 cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1028 new String[] { String.valueOf(share.getIdRemoteShared()) });
1029 } catch (RemoteException e) {
1030 Log_OC.e(TAG,
1031 "Fail to insert insert file to database "
1032 + e.getMessage());
1033 }
1034 }
1035 } else {
1036 Uri result_uri = null;
1037 if (getContentResolver() != null) {
1038 result_uri = getContentResolver().insert(
1039 ProviderTableMeta.CONTENT_URI_SHARE, cv);
1040 } else {
1041 try {
1042 result_uri = getContentProviderClient().insert(
1043 ProviderTableMeta.CONTENT_URI_SHARE, cv);
1044 } catch (RemoteException e) {
1045 Log_OC.e(TAG,
1046 "Fail to insert insert file to database "
1047 + e.getMessage());
1048 }
1049 }
1050 if (result_uri != null) {
1051 long new_id = Long.parseLong(result_uri.getPathSegments()
1052 .get(1));
1053 share.setId(new_id);
1054 }
1055 }
1056
1057 return overriden;
1058 }
1059
1060
1061 public OCShare getFirstShareByPathAndType(String path, ShareType type) {
1062 Cursor c = null;
1063 if (getContentResolver() != null) {
1064 c = getContentResolver().query(
1065 ProviderTableMeta.CONTENT_URI_SHARE,
1066 null,
1067 ProviderTableMeta.OCSHARES_PATH + "=? AND "
1068 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
1069 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1070 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
1071 null);
1072 } else {
1073 try {
1074 c = getContentProviderClient().query(
1075 ProviderTableMeta.CONTENT_URI_SHARE,
1076 null,
1077 ProviderTableMeta.OCSHARES_PATH + "=? AND "
1078 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
1079 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1080 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
1081 null);
1082
1083 } catch (RemoteException e) {
1084 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
1085 c = null;
1086 }
1087 }
1088 OCShare share = null;
1089 if (c.moveToFirst()) {
1090 share = createShareInstance(c);
1091 }
1092 c.close();
1093 return share;
1094 }
1095
1096 private OCShare createShareInstance(Cursor c) {
1097 OCShare share = null;
1098 if (c != null) {
1099 share = new OCShare(c.getString(c
1100 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
1101 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1102 share.setFileSource(c.getLong(c
1103 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
1104 share.setShareType(ShareType.fromValue(c.getInt(c
1105 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
1106 share.setPermissions(c.getInt(c
1107 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
1108 share.setSharedDate(c.getLong(c
1109 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
1110 share.setExpirationDate(c.getLong(c
1111 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
1112 share.setToken(c.getString(c
1113 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
1114 share.setSharedWithDisplayName(c.getString(c
1115 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
1116 share.setIsFolder(c.getInt(
1117 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1 ? true : false);
1118 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
1119 share.setIdRemoteShared(
1120 c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED))
1121 );
1122
1123 }
1124 return share;
1125 }
1126
1127 private boolean shareExists(String cmp_key, String value) {
1128 Cursor c;
1129 if (getContentResolver() != null) {
1130 c = getContentResolver()
1131 .query(ProviderTableMeta.CONTENT_URI_SHARE,
1132 null,
1133 cmp_key + "=? AND "
1134 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
1135 + "=?",
1136 new String[] { value, mAccount.name }, null);
1137 } else {
1138 try {
1139 c = getContentProviderClient().query(
1140 ProviderTableMeta.CONTENT_URI_SHARE,
1141 null,
1142 cmp_key + "=? AND "
1143 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1144 new String[] { value, mAccount.name }, null);
1145 } catch (RemoteException e) {
1146 Log_OC.e(TAG,
1147 "Couldn't determine file existance, assuming non existance: "
1148 + e.getMessage());
1149 return false;
1150 }
1151 }
1152 boolean retval = c.moveToFirst();
1153 c.close();
1154 return retval;
1155 }
1156
1157 private boolean shareExists(long remoteId) {
1158 return shareExists(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, String.valueOf(remoteId));
1159 }
1160
1161 private void cleanSharedFiles() {
1162 ContentValues cv = new ContentValues();
1163 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1164 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1165 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
1166 String [] whereArgs = new String[]{mAccount.name};
1167
1168 if (getContentResolver() != null) {
1169 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1170
1171 } else {
1172 try {
1173 getContentProviderClient().update(
1174 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1175 );
1176
1177 } catch (RemoteException e) {
1178 Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
1179 }
1180 }
1181 }
1182
1183 private void cleanSharedFilesInFolder(OCFile folder) {
1184 ContentValues cv = new ContentValues();
1185 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1186 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1187 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1188 ProviderTableMeta.FILE_PARENT + "=?";
1189 String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
1190
1191 if (getContentResolver() != null) {
1192 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1193
1194 } else {
1195 try {
1196 getContentProviderClient().update(
1197 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1198 );
1199
1200 } catch (RemoteException e) {
1201 Log_OC.e(TAG, "Exception in cleanSharedFilesInFolder " + e.getMessage());
1202 }
1203 }
1204 }
1205
1206 private void cleanShares() {
1207 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1208 String [] whereArgs = new String[]{mAccount.name};
1209
1210 if (getContentResolver() != null) {
1211 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1212
1213 } else {
1214 try {
1215 getContentProviderClient().delete(
1216 ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs
1217 );
1218
1219 } catch (RemoteException e) {
1220 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
1221 }
1222 }
1223 }
1224
1225 public void saveShares(Collection<OCShare> shares) {
1226 cleanShares();
1227 if (shares != null) {
1228 ArrayList<ContentProviderOperation> operations =
1229 new ArrayList<ContentProviderOperation>(shares.size());
1230
1231 // prepare operations to insert or update files to save in the given folder
1232 for (OCShare share : shares) {
1233 ContentValues cv = new ContentValues();
1234 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1235 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1236 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1237 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1238 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1239 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1240 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1241 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1242 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1243 cv.put(
1244 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1245 share.getSharedWithDisplayName()
1246 );
1247 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1248 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1249 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1250 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1251
1252 if (shareExists(share.getIdRemoteShared())) {
1253 // updating an existing file
1254 operations.add(
1255 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1256 withValues(cv).
1257 withSelection(
1258 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1259 new String[] { String.valueOf(share.getIdRemoteShared()) }
1260 ).
1261 build()
1262 );
1263
1264 } else {
1265 // adding a new file
1266 operations.add(
1267 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1268 withValues(cv).
1269 build()
1270 );
1271 }
1272 }
1273
1274 // apply operations in batch
1275 if (operations.size() > 0) {
1276 @SuppressWarnings("unused")
1277 ContentProviderResult[] results = null;
1278 Log_OC.d(TAG, "Sending " + operations.size() +
1279 " operations to FileContentProvider");
1280 try {
1281 if (getContentResolver() != null) {
1282 results = getContentResolver().applyBatch(
1283 MainApp.getAuthority(), operations
1284 );
1285
1286 } else {
1287 results = getContentProviderClient().applyBatch(operations);
1288 }
1289
1290 } catch (OperationApplicationException e) {
1291 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1292
1293 } catch (RemoteException e) {
1294 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1295 }
1296 }
1297 }
1298
1299 }
1300
1301 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1302 cleanSharedFiles();
1303
1304 if (sharedFiles != null) {
1305 ArrayList<ContentProviderOperation> operations =
1306 new ArrayList<ContentProviderOperation>(sharedFiles.size());
1307
1308 // prepare operations to insert or update files to save in the given folder
1309 for (OCFile file : sharedFiles) {
1310 ContentValues cv = new ContentValues();
1311 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1312 cv.put(
1313 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
1314 file.getModificationTimestampAtLastSyncForData()
1315 );
1316 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1317 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1318 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1319 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1320 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1321 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1322 if (!file.isFolder()) {
1323 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1324 }
1325 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1326 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1327 cv.put(
1328 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
1329 file.getLastSyncDateForData()
1330 );
1331 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
1332 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1333 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
1334 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1335 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
1336 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
1337 cv.put(
1338 ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
1339 file.needsUpdateThumbnail() ? 1 : 0
1340 );
1341
1342 boolean existsByPath = fileExists(file.getRemotePath());
1343 if (existsByPath || fileExists(file.getFileId())) {
1344 // updating an existing file
1345 operations.add(
1346 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1347 withValues(cv).
1348 withSelection(
1349 ProviderTableMeta._ID + "=?",
1350 new String[] { String.valueOf(file.getFileId()) }
1351 ).build()
1352 );
1353
1354 } else {
1355 // adding a new file
1356 operations.add(
1357 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
1358 withValues(cv).
1359 build()
1360 );
1361 }
1362 }
1363
1364 // apply operations in batch
1365 if (operations.size() > 0) {
1366 @SuppressWarnings("unused")
1367 ContentProviderResult[] results = null;
1368 Log_OC.d(TAG, "Sending " + operations.size() +
1369 " operations to FileContentProvider");
1370 try {
1371 if (getContentResolver() != null) {
1372 results = getContentResolver().applyBatch(
1373 MainApp.getAuthority(), operations
1374 );
1375
1376 } else {
1377 results = 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
1391 public void removeShare(OCShare share){
1392 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1393 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
1394 ProviderTableMeta.FILE_PATH + "=?";
1395 String [] whereArgs = new String[]{mAccount.name, share.getPath()};
1396 if (getContentProviderClient() != null) {
1397 try {
1398 getContentProviderClient().delete(share_uri, where, whereArgs);
1399 } catch (RemoteException e) {
1400 e.printStackTrace();
1401 }
1402 } else {
1403 getContentResolver().delete(share_uri, where, whereArgs);
1404 }
1405 }
1406
1407 public void saveSharesDB(ArrayList<OCShare> shares) {
1408 saveShares(shares);
1409
1410 ArrayList<OCFile> sharedFiles = new ArrayList<OCFile>();
1411
1412 for (OCShare share : shares) {
1413 // Get the path
1414 String path = share.getPath();
1415 if (share.isFolder()) {
1416 path = path + FileUtils.PATH_SEPARATOR;
1417 }
1418
1419 // Update OCFile with data from share: ShareByLink and publicLink
1420 OCFile file = getFileByPath(path);
1421 if (file != null) {
1422 if (share.getShareType().equals(ShareType.PUBLIC_LINK)) {
1423 file.setShareByLink(true);
1424 sharedFiles.add(file);
1425 }
1426 }
1427 }
1428
1429 updateSharedFiles(sharedFiles);
1430 }
1431
1432
1433 public void saveSharesInFolder(ArrayList<OCShare> shares, OCFile folder) {
1434 cleanSharedFilesInFolder(folder);
1435 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1436 operations = prepareRemoveSharesInFolder(folder, operations);
1437
1438 if (shares != null) {
1439 // prepare operations to insert or update files to save in the given folder
1440 for (OCShare share : shares) {
1441 ContentValues cv = new ContentValues();
1442 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1443 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1444 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1445 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1446 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1447 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1448 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1449 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1450 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1451 cv.put(
1452 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1453 share.getSharedWithDisplayName()
1454 );
1455 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1456 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1457 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1458 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1459
1460 /*
1461 if (shareExists(share.getIdRemoteShared())) {
1462 // updating an existing share resource
1463 operations.add(
1464 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1465 withValues(cv).
1466 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1467 new String[] { String.valueOf(share.getIdRemoteShared()) })
1468 .build());
1469
1470 } else {
1471 */
1472 // adding a new share resource
1473 operations.add(
1474 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1475 withValues(cv).
1476 build()
1477 );
1478 //}
1479 }
1480 }
1481
1482 // apply operations in batch
1483 if (operations.size() > 0) {
1484 @SuppressWarnings("unused")
1485 ContentProviderResult[] results = null;
1486 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1487 try {
1488 if (getContentResolver() != null) {
1489 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1490
1491 } else {
1492 results = getContentProviderClient().applyBatch(operations);
1493 }
1494
1495 } catch (OperationApplicationException e) {
1496 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1497
1498 } catch (RemoteException e) {
1499 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1500 }
1501 }
1502 //}
1503
1504 }
1505
1506 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
1507 OCFile folder, ArrayList<ContentProviderOperation> preparedOperations
1508 ) {
1509 if (folder != null) {
1510 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1511 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1512 String [] whereArgs = new String[]{ "", mAccount.name };
1513
1514 Vector<OCFile> files = getFolderContent(folder);
1515
1516 for (OCFile file : files) {
1517 whereArgs[0] = file.getRemotePath();
1518 preparedOperations.add(
1519 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1520 withSelection(where, whereArgs).
1521 build()
1522 );
1523 }
1524 }
1525 return preparedOperations;
1526
1527 /*
1528 if (operations.size() > 0) {
1529 try {
1530 if (getContentResolver() != null) {
1531 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1532
1533 } else {
1534 getContentProviderClient().applyBatch(operations);
1535 }
1536
1537 } catch (OperationApplicationException e) {
1538 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1539
1540 } catch (RemoteException e) {
1541 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1542 }
1543 }
1544 */
1545
1546 /*
1547 if (getContentResolver() != null) {
1548
1549 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE,
1550 where,
1551 whereArgs);
1552 } else {
1553 try {
1554 getContentProviderClient().delete( ProviderTableMeta.CONTENT_URI_SHARE,
1555 where,
1556 whereArgs);
1557
1558 } catch (RemoteException e) {
1559 Log_OC.e(TAG, "Exception deleting shares in a folder " + e.getMessage());
1560 }
1561 }
1562 */
1563 //}
1564 }
1565
1566 public void triggerMediaScan(String path) {
1567 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1568 intent.setData(Uri.fromFile(new File(path)));
1569 MainApp.getAppContext().sendBroadcast(intent);
1570 }
1571
1572 }