Merge branch 'develop' into thumbnailOOM
[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 com.owncloud.android.MainApp;
32 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
33 import com.owncloud.android.lib.common.utils.Log_OC;
34 import com.owncloud.android.lib.resources.shares.OCShare;
35 import com.owncloud.android.lib.resources.shares.ShareType;
36 import com.owncloud.android.lib.resources.files.FileUtils;
37 import com.owncloud.android.utils.FileStorageUtils;
38
39 import android.accounts.Account;
40 import android.content.ContentProviderClient;
41 import android.content.ContentProviderOperation;
42 import android.content.ContentProviderResult;
43 import android.content.ContentResolver;
44 import android.content.ContentUris;
45 import android.content.ContentValues;
46 import android.content.Intent;
47 import android.content.OperationApplicationException;
48 import android.database.Cursor;
49 import android.net.Uri;
50 import android.os.RemoteException;
51 import android.provider.MediaStore;
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) {
146 if (f != null && f.isFolder() && f.getFileId() != -1) {
147 return getFolderContent(f.getFileId());
148
149 } else {
150 return new Vector<OCFile>();
151 }
152 }
153
154
155 public Vector<OCFile> getFolderImages(OCFile folder) {
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);
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());
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) {
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 ret.add(child);
762 } while (c.moveToNext());
763 }
764
765 c.close();
766
767 Collections.sort(ret);
768
769 return ret;
770 }
771
772
773 private OCFile createRootDir() {
774 OCFile file = new OCFile(OCFile.ROOT_PATH);
775 file.setMimetype("DIR");
776 file.setParentId(FileDataStorageManager.ROOT_PARENT_ID);
777 saveFile(file);
778 return file;
779 }
780
781 private boolean fileExists(String cmp_key, String value) {
782 Cursor c;
783 if (getContentResolver() != null) {
784 c = getContentResolver()
785 .query(ProviderTableMeta.CONTENT_URI,
786 null,
787 cmp_key + "=? AND "
788 + ProviderTableMeta.FILE_ACCOUNT_OWNER
789 + "=?",
790 new String[] { value, mAccount.name }, null);
791 } else {
792 try {
793 c = getContentProviderClient().query(
794 ProviderTableMeta.CONTENT_URI,
795 null,
796 cmp_key + "=? AND "
797 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
798 new String[] { value, mAccount.name }, null);
799 } catch (RemoteException e) {
800 Log_OC.e(TAG,
801 "Couldn't determine file existance, assuming non existance: "
802 + e.getMessage());
803 return false;
804 }
805 }
806 boolean retval = c.moveToFirst();
807 c.close();
808 return retval;
809 }
810
811 private Cursor getCursorForValue(String key, String value) {
812 Cursor c = null;
813 if (getContentResolver() != null) {
814 c = getContentResolver()
815 .query(ProviderTableMeta.CONTENT_URI,
816 null,
817 key + "=? AND "
818 + ProviderTableMeta.FILE_ACCOUNT_OWNER
819 + "=?",
820 new String[] { value, mAccount.name }, null);
821 } else {
822 try {
823 c = getContentProviderClient().query(
824 ProviderTableMeta.CONTENT_URI,
825 null,
826 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
827 + "=?", new String[] { value, mAccount.name },
828 null);
829 } catch (RemoteException e) {
830 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
831 c = null;
832 }
833 }
834 return c;
835 }
836
837
838 private OCFile createFileInstance(Cursor c) {
839 OCFile file = null;
840 if (c != null) {
841 file = new OCFile(c.getString(c
842 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
843 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
844 file.setParentId(c.getLong(c
845 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
846 file.setMimetype(c.getString(c
847 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
848 if (!file.isFolder()) {
849 file.setStoragePath(c.getString(c
850 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
851 if (file.getStoragePath() == null) {
852 // try to find existing file and bind it with current account;
853 // with the current update of SynchronizeFolderOperation, this won't be
854 // necessary anymore after a full synchronization of the account
855 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
856 if (f.exists()) {
857 file.setStoragePath(f.getAbsolutePath());
858 file.setLastSyncDateForData(f.lastModified());
859 }
860 }
861 }
862 file.setFileLength(c.getLong(c
863 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
864 file.setCreationTimestamp(c.getLong(c
865 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
866 file.setModificationTimestamp(c.getLong(c
867 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
868 file.setModificationTimestampAtLastSyncForData(c.getLong(c
869 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)));
870 file.setLastSyncDateForProperties(c.getLong(c
871 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
872 file.setLastSyncDateForData(c.getLong(c.
873 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
874 file.setKeepInSync(c.getInt(
875 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
876 file.setEtag(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)));
877 file.setShareByLink(c.getInt(
878 c.getColumnIndex(ProviderTableMeta.FILE_SHARE_BY_LINK)) == 1 ? true : false);
879 file.setPublicLink(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PUBLIC_LINK)));
880 file.setPermissions(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PERMISSIONS)));
881 file.setRemoteId(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID)));
882 file.setNeedsUpdateThumbnail(c.getInt(
883 c.getColumnIndex(ProviderTableMeta.FILE_UPDATE_THUMBNAIL)) == 1 ? true : false);
884 file.setDownloading(c.getInt(
885 c.getColumnIndex(ProviderTableMeta.FILE_IS_DOWNLOADING)) == 1 ? true : false);
886
887 }
888 return file;
889 }
890
891 /**
892 * Returns if the file/folder is shared by link or not
893 * @param path Path of the file/folder
894 * @return
895 */
896 public boolean isShareByLink(String path) {
897 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
898 OCFile file = null;
899 if (c.moveToFirst()) {
900 file = createFileInstance(c);
901 }
902 c.close();
903 return file.isShareByLink();
904 }
905
906 /**
907 * Returns the public link of the file/folder
908 * @param path Path of the file/folder
909 * @return
910 */
911 public String getPublicLink(String path) {
912 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
913 OCFile file = null;
914 if (c.moveToFirst()) {
915 file = createFileInstance(c);
916 }
917 c.close();
918 return file.getPublicLink();
919 }
920
921
922 // Methods for Shares
923 public boolean saveShare(OCShare share) {
924 boolean overriden = false;
925 ContentValues cv = new ContentValues();
926 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
927 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
928 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
929 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
930 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
931 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
932 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
933 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
934 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
935 cv.put(
936 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
937 share.getSharedWithDisplayName()
938 );
939 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
940 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
941 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
942 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
943
944 if (shareExists(share.getIdRemoteShared())) { // for renamed files
945
946 overriden = true;
947 if (getContentResolver() != null) {
948 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
949 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
950 new String[] { String.valueOf(share.getIdRemoteShared()) });
951 } else {
952 try {
953 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
954 cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
955 new String[] { String.valueOf(share.getIdRemoteShared()) });
956 } catch (RemoteException e) {
957 Log_OC.e(TAG,
958 "Fail to insert insert file to database "
959 + e.getMessage());
960 }
961 }
962 } else {
963 Uri result_uri = null;
964 if (getContentResolver() != null) {
965 result_uri = getContentResolver().insert(
966 ProviderTableMeta.CONTENT_URI_SHARE, cv);
967 } else {
968 try {
969 result_uri = getContentProviderClient().insert(
970 ProviderTableMeta.CONTENT_URI_SHARE, cv);
971 } catch (RemoteException e) {
972 Log_OC.e(TAG,
973 "Fail to insert insert file to database "
974 + e.getMessage());
975 }
976 }
977 if (result_uri != null) {
978 long new_id = Long.parseLong(result_uri.getPathSegments()
979 .get(1));
980 share.setId(new_id);
981 }
982 }
983
984 return overriden;
985 }
986
987
988 public OCShare getFirstShareByPathAndType(String path, ShareType type) {
989 Cursor c = null;
990 if (getContentResolver() != null) {
991 c = getContentResolver().query(
992 ProviderTableMeta.CONTENT_URI_SHARE,
993 null,
994 ProviderTableMeta.OCSHARES_PATH + "=? AND "
995 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
996 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
997 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
998 null);
999 } else {
1000 try {
1001 c = getContentProviderClient().query(
1002 ProviderTableMeta.CONTENT_URI_SHARE,
1003 null,
1004 ProviderTableMeta.OCSHARES_PATH + "=? AND "
1005 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
1006 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1007 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
1008 null);
1009
1010 } catch (RemoteException e) {
1011 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
1012 c = null;
1013 }
1014 }
1015 OCShare share = null;
1016 if (c.moveToFirst()) {
1017 share = createShareInstance(c);
1018 }
1019 c.close();
1020 return share;
1021 }
1022
1023 private OCShare createShareInstance(Cursor c) {
1024 OCShare share = null;
1025 if (c != null) {
1026 share = new OCShare(c.getString(c
1027 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
1028 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1029 share.setFileSource(c.getLong(c
1030 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
1031 share.setShareType(ShareType.fromValue(c.getInt(c
1032 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
1033 share.setPermissions(c.getInt(c
1034 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
1035 share.setSharedDate(c.getLong(c
1036 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
1037 share.setExpirationDate(c.getLong(c
1038 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
1039 share.setToken(c.getString(c
1040 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
1041 share.setSharedWithDisplayName(c.getString(c
1042 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
1043 share.setIsFolder(c.getInt(
1044 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1 ? true : false);
1045 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
1046 share.setIdRemoteShared(
1047 c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED))
1048 );
1049
1050 }
1051 return share;
1052 }
1053
1054 private boolean shareExists(String cmp_key, String value) {
1055 Cursor c;
1056 if (getContentResolver() != null) {
1057 c = getContentResolver()
1058 .query(ProviderTableMeta.CONTENT_URI_SHARE,
1059 null,
1060 cmp_key + "=? AND "
1061 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
1062 + "=?",
1063 new String[] { value, mAccount.name }, null);
1064 } else {
1065 try {
1066 c = getContentProviderClient().query(
1067 ProviderTableMeta.CONTENT_URI_SHARE,
1068 null,
1069 cmp_key + "=? AND "
1070 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1071 new String[] { value, mAccount.name }, null);
1072 } catch (RemoteException e) {
1073 Log_OC.e(TAG,
1074 "Couldn't determine file existance, assuming non existance: "
1075 + e.getMessage());
1076 return false;
1077 }
1078 }
1079 boolean retval = c.moveToFirst();
1080 c.close();
1081 return retval;
1082 }
1083
1084 private boolean shareExists(long remoteId) {
1085 return shareExists(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, String.valueOf(remoteId));
1086 }
1087
1088 private void cleanSharedFiles() {
1089 ContentValues cv = new ContentValues();
1090 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1091 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1092 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
1093 String [] whereArgs = new String[]{mAccount.name};
1094
1095 if (getContentResolver() != null) {
1096 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1097
1098 } else {
1099 try {
1100 getContentProviderClient().update(
1101 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1102 );
1103
1104 } catch (RemoteException e) {
1105 Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
1106 }
1107 }
1108 }
1109
1110 private void cleanSharedFilesInFolder(OCFile folder) {
1111 ContentValues cv = new ContentValues();
1112 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1113 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1114 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1115 ProviderTableMeta.FILE_PARENT + "=?";
1116 String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
1117
1118 if (getContentResolver() != null) {
1119 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1120
1121 } else {
1122 try {
1123 getContentProviderClient().update(
1124 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1125 );
1126
1127 } catch (RemoteException e) {
1128 Log_OC.e(TAG, "Exception in cleanSharedFilesInFolder " + e.getMessage());
1129 }
1130 }
1131 }
1132
1133 private void cleanShares() {
1134 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1135 String [] whereArgs = new String[]{mAccount.name};
1136
1137 if (getContentResolver() != null) {
1138 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1139
1140 } else {
1141 try {
1142 getContentProviderClient().delete(
1143 ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs
1144 );
1145
1146 } catch (RemoteException e) {
1147 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
1148 }
1149 }
1150 }
1151
1152 public void saveShares(Collection<OCShare> shares) {
1153 cleanShares();
1154 if (shares != null) {
1155 ArrayList<ContentProviderOperation> operations =
1156 new ArrayList<ContentProviderOperation>(shares.size());
1157
1158 // prepare operations to insert or update files to save in the given folder
1159 for (OCShare share : shares) {
1160 ContentValues cv = new ContentValues();
1161 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1162 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1163 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1164 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1165 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1166 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1167 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1168 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1169 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1170 cv.put(
1171 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1172 share.getSharedWithDisplayName()
1173 );
1174 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1175 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1176 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1177 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1178
1179 if (shareExists(share.getIdRemoteShared())) {
1180 // updating an existing file
1181 operations.add(
1182 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1183 withValues(cv).
1184 withSelection(
1185 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1186 new String[] { String.valueOf(share.getIdRemoteShared()) }
1187 ).
1188 build()
1189 );
1190
1191 } else {
1192 // adding a new file
1193 operations.add(
1194 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1195 withValues(cv).
1196 build()
1197 );
1198 }
1199 }
1200
1201 // apply operations in batch
1202 if (operations.size() > 0) {
1203 @SuppressWarnings("unused")
1204 ContentProviderResult[] results = null;
1205 Log_OC.d(TAG, "Sending " + operations.size() +
1206 " operations to FileContentProvider");
1207 try {
1208 if (getContentResolver() != null) {
1209 results = getContentResolver().applyBatch(
1210 MainApp.getAuthority(), operations
1211 );
1212
1213 } else {
1214 results = getContentProviderClient().applyBatch(operations);
1215 }
1216
1217 } catch (OperationApplicationException e) {
1218 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1219
1220 } catch (RemoteException e) {
1221 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1222 }
1223 }
1224 }
1225
1226 }
1227
1228 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1229 cleanSharedFiles();
1230
1231 if (sharedFiles != null) {
1232 ArrayList<ContentProviderOperation> operations =
1233 new ArrayList<ContentProviderOperation>(sharedFiles.size());
1234
1235 // prepare operations to insert or update files to save in the given folder
1236 for (OCFile file : sharedFiles) {
1237 ContentValues cv = new ContentValues();
1238 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1239 cv.put(
1240 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
1241 file.getModificationTimestampAtLastSyncForData()
1242 );
1243 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1244 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1245 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1246 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1247 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1248 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1249 if (!file.isFolder()) {
1250 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1251 }
1252 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1253 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1254 cv.put(
1255 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
1256 file.getLastSyncDateForData()
1257 );
1258 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
1259 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1260 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
1261 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1262 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
1263 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
1264 cv.put(
1265 ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
1266 file.needsUpdateThumbnail() ? 1 : 0
1267 );
1268 cv.put(
1269 ProviderTableMeta.FILE_IS_DOWNLOADING,
1270 file.isDownloading() ? 1 : 0
1271 );
1272
1273 boolean existsByPath = fileExists(file.getRemotePath());
1274 if (existsByPath || fileExists(file.getFileId())) {
1275 // updating an existing file
1276 operations.add(
1277 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1278 withValues(cv).
1279 withSelection(
1280 ProviderTableMeta._ID + "=?",
1281 new String[] { String.valueOf(file.getFileId()) }
1282 ).build()
1283 );
1284
1285 } else {
1286 // adding a new file
1287 operations.add(
1288 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
1289 withValues(cv).
1290 build()
1291 );
1292 }
1293 }
1294
1295 // apply operations in batch
1296 if (operations.size() > 0) {
1297 @SuppressWarnings("unused")
1298 ContentProviderResult[] results = null;
1299 Log_OC.d(TAG, "Sending " + operations.size() +
1300 " operations to FileContentProvider");
1301 try {
1302 if (getContentResolver() != null) {
1303 results = getContentResolver().applyBatch(
1304 MainApp.getAuthority(), operations
1305 );
1306
1307 } else {
1308 results = getContentProviderClient().applyBatch(operations);
1309 }
1310
1311 } catch (OperationApplicationException e) {
1312 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1313
1314 } catch (RemoteException e) {
1315 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1316 }
1317 }
1318 }
1319
1320 }
1321
1322 public void removeShare(OCShare share){
1323 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1324 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
1325 ProviderTableMeta.FILE_PATH + "=?";
1326 String [] whereArgs = new String[]{mAccount.name, share.getPath()};
1327 if (getContentProviderClient() != null) {
1328 try {
1329 getContentProviderClient().delete(share_uri, where, whereArgs);
1330 } catch (RemoteException e) {
1331 e.printStackTrace();
1332 }
1333 } else {
1334 getContentResolver().delete(share_uri, where, whereArgs);
1335 }
1336 }
1337
1338 public void saveSharesDB(ArrayList<OCShare> shares) {
1339 saveShares(shares);
1340
1341 ArrayList<OCFile> sharedFiles = new ArrayList<OCFile>();
1342
1343 for (OCShare share : shares) {
1344 // Get the path
1345 String path = share.getPath();
1346 if (share.isFolder()) {
1347 path = path + FileUtils.PATH_SEPARATOR;
1348 }
1349
1350 // Update OCFile with data from share: ShareByLink and publicLink
1351 OCFile file = getFileByPath(path);
1352 if (file != null) {
1353 if (share.getShareType().equals(ShareType.PUBLIC_LINK)) {
1354 file.setShareByLink(true);
1355 sharedFiles.add(file);
1356 }
1357 }
1358 }
1359
1360 updateSharedFiles(sharedFiles);
1361 }
1362
1363
1364 public void saveSharesInFolder(ArrayList<OCShare> shares, OCFile folder) {
1365 cleanSharedFilesInFolder(folder);
1366 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1367 operations = prepareRemoveSharesInFolder(folder, operations);
1368
1369 if (shares != null) {
1370 // prepare operations to insert or update files to save in the given folder
1371 for (OCShare share : shares) {
1372 ContentValues cv = new ContentValues();
1373 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1374 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1375 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1376 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1377 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1378 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1379 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1380 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1381 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1382 cv.put(
1383 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1384 share.getSharedWithDisplayName()
1385 );
1386 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1387 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1388 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1389 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1390
1391 /*
1392 if (shareExists(share.getIdRemoteShared())) {
1393 // updating an existing share resource
1394 operations.add(
1395 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1396 withValues(cv).
1397 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1398 new String[] { String.valueOf(share.getIdRemoteShared()) })
1399 .build());
1400
1401 } else {
1402 */
1403 // adding a new share resource
1404 operations.add(
1405 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1406 withValues(cv).
1407 build()
1408 );
1409 //}
1410 }
1411 }
1412
1413 // apply operations in batch
1414 if (operations.size() > 0) {
1415 @SuppressWarnings("unused")
1416 ContentProviderResult[] results = null;
1417 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1418 try {
1419 if (getContentResolver() != null) {
1420 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1421
1422 } else {
1423 results = getContentProviderClient().applyBatch(operations);
1424 }
1425
1426 } catch (OperationApplicationException e) {
1427 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1428
1429 } catch (RemoteException e) {
1430 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1431 }
1432 }
1433 //}
1434
1435 }
1436
1437 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
1438 OCFile folder, ArrayList<ContentProviderOperation> preparedOperations
1439 ) {
1440 if (folder != null) {
1441 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1442 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1443 String [] whereArgs = new String[]{ "", mAccount.name };
1444
1445 Vector<OCFile> files = getFolderContent(folder);
1446
1447 for (OCFile file : files) {
1448 whereArgs[0] = file.getRemotePath();
1449 preparedOperations.add(
1450 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1451 withSelection(where, whereArgs).
1452 build()
1453 );
1454 }
1455 }
1456 return preparedOperations;
1457
1458 /*
1459 if (operations.size() > 0) {
1460 try {
1461 if (getContentResolver() != null) {
1462 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1463
1464 } else {
1465 getContentProviderClient().applyBatch(operations);
1466 }
1467
1468 } catch (OperationApplicationException e) {
1469 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1470
1471 } catch (RemoteException e) {
1472 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1473 }
1474 }
1475 */
1476
1477 /*
1478 if (getContentResolver() != null) {
1479
1480 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE,
1481 where,
1482 whereArgs);
1483 } else {
1484 try {
1485 getContentProviderClient().delete( ProviderTableMeta.CONTENT_URI_SHARE,
1486 where,
1487 whereArgs);
1488
1489 } catch (RemoteException e) {
1490 Log_OC.e(TAG, "Exception deleting shares in a folder " + e.getMessage());
1491 }
1492 }
1493 */
1494 //}
1495 }
1496
1497 public void triggerMediaScan(String path) {
1498 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1499 intent.setData(Uri.fromFile(new File(path)));
1500 MainApp.getAppContext().sendBroadcast(intent);
1501 }
1502
1503 public void deleteFileInMediaScan(String path) {
1504
1505 String mimetypeString = FileStorageUtils.getMimeTypeFromName(path);
1506 ContentResolver contentResolver = getContentResolver();
1507
1508 if (contentResolver != null) {
1509 if (mimetypeString.startsWith("image/")) {
1510 // Images
1511 contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1512 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1513 } else if (mimetypeString.startsWith("audio/")) {
1514 // Audio
1515 contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1516 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1517 } else if (mimetypeString.startsWith("video/")) {
1518 // Video
1519 contentResolver.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1520 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1521 }
1522 } else {
1523 ContentProviderClient contentProviderClient = getContentProviderClient();
1524 try {
1525 if (mimetypeString.startsWith("image/")) {
1526 // Images
1527 contentProviderClient.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1528 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1529 } else if (mimetypeString.startsWith("audio/")) {
1530 // Audio
1531 contentProviderClient.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1532 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1533 } else if (mimetypeString.startsWith("video/")) {
1534 // Video
1535 contentProviderClient.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1536 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1537 }
1538 } catch (RemoteException e) {
1539 Log_OC.e(TAG, "Exception deleting media file in MediaStore " + e.getMessage());
1540 }
1541 }
1542
1543 }
1544
1545 }