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