2 * ownCloud Android client application
4 * Copyright (C) 2012 Bartek Przybylski
5 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
21 package com
.owncloud
.android
.datamodel
;
24 import java
.util
.ArrayList
;
25 import java
.util
.Collection
;
26 import java
.util
.Collections
;
27 import java
.util
.HashSet
;
28 import java
.util
.Iterator
;
29 import java
.util
.List
;
31 import java
.util
.Vector
;
33 import android
.accounts
.Account
;
34 import android
.content
.ContentProviderClient
;
35 import android
.content
.ContentProviderOperation
;
36 import android
.content
.ContentProviderResult
;
37 import android
.content
.ContentResolver
;
38 import android
.content
.ContentUris
;
39 import android
.content
.ContentValues
;
40 import android
.content
.Intent
;
41 import android
.content
.OperationApplicationException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.RemoteException
;
45 import android
.provider
.MediaStore
;
47 import com
.owncloud
.android
.MainApp
;
48 import com
.owncloud
.android
.db
.ProviderMeta
.ProviderTableMeta
;
49 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
50 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
51 import com
.owncloud
.android
.lib
.resources
.shares
.OCShare
;
52 import com
.owncloud
.android
.lib
.resources
.shares
.ShareType
;
53 import com
.owncloud
.android
.utils
.FileStorageUtils
;
55 import java
.io
.FileInputStream
;
56 import java
.io
.FileOutputStream
;
57 import java
.io
.IOException
;
58 import java
.io
.InputStream
;
59 import java
.io
.OutputStream
;
61 public class FileDataStorageManager
{
63 public static final int ROOT_PARENT_ID
= 0;
65 private ContentResolver mContentResolver
;
66 private ContentProviderClient mContentProviderClient
;
67 private Account mAccount
;
69 private static String TAG
= FileDataStorageManager
.class.getSimpleName();
72 public FileDataStorageManager(Account account
, ContentResolver cr
) {
73 mContentProviderClient
= null
;
74 mContentResolver
= cr
;
78 public FileDataStorageManager(Account account
, ContentProviderClient cp
) {
79 mContentProviderClient
= cp
;
80 mContentResolver
= null
;
85 public void setAccount(Account account
) {
89 public Account
getAccount() {
93 public void setContentResolver(ContentResolver cr
) {
94 mContentResolver
= cr
;
97 public ContentResolver
getContentResolver() {
98 return mContentResolver
;
101 public void setContentProviderClient(ContentProviderClient cp
) {
102 mContentProviderClient
= cp
;
105 public ContentProviderClient
getContentProviderClient() {
106 return mContentProviderClient
;
110 public OCFile
getFileByPath(String path
) {
111 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_PATH
, path
);
113 if (c
.moveToFirst()) {
114 file
= createFileInstance(c
);
117 if (file
== null
&& OCFile
.ROOT_PATH
.equals(path
)) {
118 return createRootDir(); // root should always exist
124 public OCFile
getFileById(long id
) {
125 Cursor c
= getCursorForValue(ProviderTableMeta
._ID
, String
.valueOf(id
));
127 if (c
.moveToFirst()) {
128 file
= createFileInstance(c
);
134 public OCFile
getFileByLocalPath(String path
) {
135 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_STORAGE_PATH
, path
);
137 if (c
.moveToFirst()) {
138 file
= createFileInstance(c
);
144 public boolean fileExists(long id
) {
145 return fileExists(ProviderTableMeta
._ID
, String
.valueOf(id
));
148 public boolean fileExists(String path
) {
149 return fileExists(ProviderTableMeta
.FILE_PATH
, path
);
153 public Vector
<OCFile
> getFolderContent(OCFile f
/*, boolean onlyOnDevice*/) {
154 if (f
!= null
&& f
.isFolder() && f
.getFileId() != -1) {
155 // TODO Enable when "On Device" is recovered ?
156 return getFolderContent(f
.getFileId()/*, onlyOnDevice*/);
159 return new Vector
<OCFile
>();
164 public Vector
<OCFile
> getFolderImages(OCFile folder
/*, boolean onlyOnDevice*/) {
165 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
166 if (folder
!= null
) {
167 // TODO better implementation, filtering in the access to database instead of here
168 // TODO Enable when "On Device" is recovered ?
169 Vector
<OCFile
> tmp
= getFolderContent(folder
/*, onlyOnDevice*/);
170 OCFile current
= null
;
171 for (int i
=0; i
<tmp
.size(); i
++) {
172 current
= tmp
.get(i
);
173 if (current
.isImage()) {
181 public boolean saveFile(OCFile file
) {
182 boolean overriden
= false
;
183 ContentValues cv
= new ContentValues();
184 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
186 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
187 file
.getModificationTimestampAtLastSyncForData()
189 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
190 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
191 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
192 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
193 //if (file.getParentId() != DataStorageManager.ROOT_PARENT_ID)
194 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
195 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
196 if (!file
.isFolder())
197 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
198 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
199 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
200 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, file
.getLastSyncDateForData());
201 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
202 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
203 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
204 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
205 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
206 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
207 cv
.put(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
, file
.needsUpdateThumbnail());
208 cv
.put(ProviderTableMeta
.FILE_IS_DOWNLOADING
, file
.isDownloading());
209 cv
.put(ProviderTableMeta
.FILE_IN_CONFLICT
, file
.isInConflict());
211 boolean sameRemotePath
= fileExists(file
.getRemotePath());
212 if (sameRemotePath
|| fileExists(file
.getFileId())) { // for renamed files; no more delete and create
214 OCFile oldFile
= null
;
215 if (sameRemotePath
) {
216 oldFile
= getFileByPath(file
.getRemotePath());
217 file
.setFileId(oldFile
.getFileId());
219 oldFile
= getFileById(file
.getFileId());
223 if (getContentResolver() != null
) {
224 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
,
225 ProviderTableMeta
._ID
+ "=?",
226 new String
[]{String
.valueOf(file
.getFileId())});
229 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
,
230 cv
, ProviderTableMeta
._ID
+ "=?",
231 new String
[]{String
.valueOf(file
.getFileId())});
232 } catch (RemoteException e
) {
234 "Fail to insert insert file to database "
239 Uri result_uri
= null
;
240 if (getContentResolver() != null
) {
241 result_uri
= getContentResolver().insert(
242 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
245 result_uri
= getContentProviderClient().insert(
246 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
247 } catch (RemoteException e
) {
249 "Fail to insert insert file to database "
253 if (result_uri
!= null
) {
254 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
256 file
.setFileId(new_id
);
260 // if (file.isFolder()) {
261 // updateFolderSize(file.getFileId());
263 // updateFolderSize(file.getParentId());
271 * Inserts or updates the list of files contained in a given folder.
273 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
274 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
277 * @param updatedFiles
278 * @param filesToRemove
280 public void saveFolder(
281 OCFile folder
, Collection
<OCFile
> updatedFiles
, Collection
<OCFile
> filesToRemove
284 Log_OC
.d(TAG
, "Saving folder " + folder
.getRemotePath() + " with " + updatedFiles
.size()
285 + " children and " + filesToRemove
.size() + " files to remove");
287 ArrayList
<ContentProviderOperation
> operations
=
288 new ArrayList
<ContentProviderOperation
>(updatedFiles
.size());
290 // prepare operations to insert or update files to save in the given folder
291 for (OCFile file
: updatedFiles
) {
292 ContentValues cv
= new ContentValues();
293 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
295 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
296 file
.getModificationTimestampAtLastSyncForData()
298 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
299 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
300 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
301 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
302 //cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
303 cv
.put(ProviderTableMeta
.FILE_PARENT
, folder
.getFileId());
304 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
305 if (!file
.isFolder()) {
306 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
308 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
309 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
310 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, file
.getLastSyncDateForData());
311 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
312 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
313 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
314 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
315 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
316 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
317 cv
.put(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
, file
.needsUpdateThumbnail());
318 cv
.put(ProviderTableMeta
.FILE_IS_DOWNLOADING
, file
.isDownloading());
319 cv
.put(ProviderTableMeta
.FILE_IN_CONFLICT
, file
.isInConflict());
321 boolean existsByPath
= fileExists(file
.getRemotePath());
322 if (existsByPath
|| fileExists(file
.getFileId())) {
323 // updating an existing file
324 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
326 withSelection(ProviderTableMeta
._ID
+ "=?",
327 new String
[]{String
.valueOf(file
.getFileId())})
332 operations
.add(ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
333 withValues(cv
).build());
337 // prepare operations to remove files in the given folder
338 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " +
339 ProviderTableMeta
.FILE_PATH
+ "=?";
340 String
[] whereArgs
= null
;
341 for (OCFile file
: filesToRemove
) {
342 if (file
.getParentId() == folder
.getFileId()) {
343 whereArgs
= new String
[]{mAccount
.name
, file
.getRemotePath()};
344 //Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, "" + file.getFileId());
345 if (file
.isFolder()) {
346 operations
.add(ContentProviderOperation
.newDelete(
347 ContentUris
.withAppendedId(
348 ProviderTableMeta
.CONTENT_URI_DIR
, file
.getFileId()
350 ).withSelection(where
, whereArgs
).build());
353 new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
354 if (localFolder
.exists()) {
355 removeLocalFolder(localFolder
);
358 operations
.add(ContentProviderOperation
.newDelete(
359 ContentUris
.withAppendedId(
360 ProviderTableMeta
.CONTENT_URI_FILE
, file
.getFileId()
362 ).withSelection(where
, whereArgs
).build());
365 String path
= file
.getStoragePath();
366 new File(path
).delete();
367 triggerMediaScan(path
); // notify MediaScanner about removed file
373 // update metadata of folder
374 ContentValues cv
= new ContentValues();
375 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, folder
.getModificationTimestamp());
377 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
378 folder
.getModificationTimestampAtLastSyncForData()
380 cv
.put(ProviderTableMeta
.FILE_CREATION
, folder
.getCreationTimestamp());
381 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, 0);
382 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, folder
.getMimetype());
383 cv
.put(ProviderTableMeta
.FILE_NAME
, folder
.getFileName());
384 cv
.put(ProviderTableMeta
.FILE_PARENT
, folder
.getParentId());
385 cv
.put(ProviderTableMeta
.FILE_PATH
, folder
.getRemotePath());
386 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
387 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, folder
.getLastSyncDateForProperties());
388 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, folder
.getLastSyncDateForData());
389 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, folder
.isFavorite() ?
1 : 0);
390 cv
.put(ProviderTableMeta
.FILE_ETAG
, folder
.getEtag());
391 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, folder
.isShareByLink() ?
1 : 0);
392 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, folder
.getPublicLink());
393 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, folder
.getPermissions());
394 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, folder
.getRemoteId());
396 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
398 withSelection(ProviderTableMeta
._ID
+ "=?",
399 new String
[]{String
.valueOf(folder
.getFileId())})
402 // apply operations in batch
403 ContentProviderResult
[] results
= null
;
404 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
406 if (getContentResolver() != null
) {
407 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
410 results
= getContentProviderClient().applyBatch(operations
);
413 } catch (OperationApplicationException e
) {
414 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
416 } catch (RemoteException e
) {
417 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
420 // update new id in file objects for insertions
421 if (results
!= null
) {
423 Iterator
<OCFile
> filesIt
= updatedFiles
.iterator();
425 for (int i
= 0; i
< results
.length
; i
++) {
426 if (filesIt
.hasNext()) {
427 file
= filesIt
.next();
431 if (results
[i
].uri
!= null
) {
432 newId
= Long
.parseLong(results
[i
].uri
.getPathSegments().get(1));
433 //updatedFiles.get(i).setFileId(newId);
435 file
.setFileId(newId
);
441 //updateFolderSize(folder.getFileId());
450 // private void updateFolderSize(long id) {
451 // if (id > FileDataStorageManager.ROOT_PARENT_ID) {
452 // Log_OC.d(TAG, "Updating size of " + id);
453 // if (getContentResolver() != null) {
454 // getContentResolver().update(ProviderTableMeta.CONTENT_URI_DIR,
455 // new ContentValues(),
456 // won't be used, but cannot be null; crashes in KLP
457 // ProviderTableMeta._ID + "=?",
458 // new String[] { String.valueOf(id) });
461 // getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_DIR,
462 // new ContentValues(),
463 // won't be used, but cannot be null; crashes in KLP
464 // ProviderTableMeta._ID + "=?",
465 // new String[] { String.valueOf(id) });
467 // } catch (RemoteException e) {
469 // TAG, "Exception in update of folder size through compatibility patch " + e.getMessage());
473 // Log_OC.e(TAG, "not updating size for folder " + id);
478 public boolean removeFile(OCFile file
, boolean removeDBData
, boolean removeLocalCopy
) {
479 boolean success
= true
;
481 if (file
.isFolder()) {
482 success
= removeFolder(file
, removeDBData
, removeLocalCopy
);
486 //Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
487 Uri file_uri
= ContentUris
.withAppendedId(ProviderTableMeta
.CONTENT_URI_FILE
, file
.getFileId());
488 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " + ProviderTableMeta
.FILE_PATH
+ "=?";
489 String
[] whereArgs
= new String
[]{mAccount
.name
, file
.getRemotePath()};
491 if (getContentProviderClient() != null
) {
493 deleted
= getContentProviderClient().delete(file_uri
, where
, whereArgs
);
494 } catch (RemoteException e
) {
498 deleted
= getContentResolver().delete(file_uri
, where
, whereArgs
);
500 success
&= (deleted
> 0);
502 String localPath
= file
.getStoragePath();
503 if (removeLocalCopy
&& file
.isDown() && localPath
!= null
&& success
) {
504 success
= new File(localPath
).delete();
506 deleteFileInMediaScan(localPath
);
508 if (!removeDBData
&& success
) {
509 // maybe unnecessary, but should be checked TODO remove if unnecessary
510 file
.setStoragePath(null
);
520 public boolean removeFolder(OCFile folder
, boolean removeDBData
, boolean removeLocalContent
) {
521 boolean success
= true
;
522 if (folder
!= null
&& folder
.isFolder()) {
523 if (removeDBData
&& folder
.getFileId() != -1) {
524 success
= removeFolderInDb(folder
);
526 if (removeLocalContent
&& success
) {
527 success
= removeLocalFolder(folder
);
533 private boolean removeFolderInDb(OCFile folder
) {
534 Uri folder_uri
= Uri
.withAppendedPath(ProviderTableMeta
.CONTENT_URI_DIR
, "" +
535 folder
.getFileId()); // URI for recursive deletion
536 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " +
537 ProviderTableMeta
.FILE_PATH
+ "=?";
538 String
[] whereArgs
= new String
[]{mAccount
.name
, folder
.getRemotePath()};
540 if (getContentProviderClient() != null
) {
542 deleted
= getContentProviderClient().delete(folder_uri
, where
, whereArgs
);
543 } catch (RemoteException e
) {
547 deleted
= getContentResolver().delete(folder_uri
, where
, whereArgs
);
552 private boolean removeLocalFolder(OCFile folder
) {
553 boolean success
= true
;
554 String localFolderPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, folder
);
555 File localFolder
= new File(localFolderPath
);
556 if (localFolder
.exists()) {
557 // stage 1: remove the local files already registered in the files database
558 // TODO Enable when "On Device" is recovered ?
559 Vector
<OCFile
> files
= getFolderContent(folder
.getFileId()/*, false*/);
561 for (OCFile file
: files
) {
562 if (file
.isFolder()) {
563 success
&= removeLocalFolder(file
);
566 File localFile
= new File(file
.getStoragePath());
567 success
&= localFile
.delete();
569 // notify MediaScanner about removed file
570 deleteFileInMediaScan(file
.getStoragePath());
571 file
.setStoragePath(null
);
579 // stage 2: remove the folder itself and any local file inside out of sync;
580 // for instance, after clearing the app cache or reinstalling
581 success
&= removeLocalFolder(localFolder
);
586 private boolean removeLocalFolder(File localFolder
) {
587 boolean success
= true
;
588 File
[] localFiles
= localFolder
.listFiles();
589 if (localFiles
!= null
) {
590 for (File localFile
: localFiles
) {
591 if (localFile
.isDirectory()) {
592 success
&= removeLocalFolder(localFile
);
594 String path
= localFile
.getAbsolutePath();
595 success
&= localFile
.delete();
599 success
&= localFolder
.delete();
605 * Updates database and file system for a file or folder that was moved to a different location.
607 * TODO explore better (faster) implementations
608 * TODO throw exceptions up !
610 public void moveLocalFile(OCFile file
, String targetPath
, String targetParentPath
) {
612 if (file
!= null
&& file
.fileExists() && !OCFile
.ROOT_PATH
.equals(file
.getFileName())) {
614 OCFile targetParent
= getFileByPath(targetParentPath
);
615 if (targetParent
== null
) {
616 throw new IllegalStateException("Parent folder of the target path does not exist!!");
619 /// 1. get all the descendants of the moved element in a single QUERY
621 if (getContentProviderClient() != null
) {
623 c
= getContentProviderClient().query(
624 ProviderTableMeta
.CONTENT_URI
,
626 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
627 ProviderTableMeta
.FILE_PATH
+ " LIKE ? ",
630 file
.getRemotePath() + "%"
632 ProviderTableMeta
.FILE_PATH
+ " ASC "
634 } catch (RemoteException e
) {
635 Log_OC
.e(TAG
, e
.getMessage());
639 c
= getContentResolver().query(
640 ProviderTableMeta
.CONTENT_URI
,
642 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
643 ProviderTableMeta
.FILE_PATH
+ " LIKE ? ",
646 file
.getRemotePath() + "%"
648 ProviderTableMeta
.FILE_PATH
+ " ASC "
652 /// 2. prepare a batch of update operations to change all the descendants
653 ArrayList
<ContentProviderOperation
> operations
=
654 new ArrayList
<ContentProviderOperation
>(c
.getCount());
655 String defaultSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
656 List
<String
> originalPathsToTriggerMediaScan
= new ArrayList
<String
>();
657 List
<String
> newPathsToTriggerMediaScan
= new ArrayList
<String
>();
658 if (c
.moveToFirst()) {
659 int lengthOfOldPath
= file
.getRemotePath().length();
660 int lengthOfOldStoragePath
= defaultSavePath
.length() + lengthOfOldPath
;
662 ContentValues cv
= new ContentValues(); // keep construction in the loop
663 OCFile child
= createFileInstance(c
);
665 ProviderTableMeta
.FILE_PATH
,
666 targetPath
+ child
.getRemotePath().substring(lengthOfOldPath
)
668 if (child
.getStoragePath() != null
&&
669 child
.getStoragePath().startsWith(defaultSavePath
)) {
670 // update link to downloaded content - but local move is not done here!
671 String targetLocalPath
= defaultSavePath
+ targetPath
+
672 child
.getStoragePath().substring(lengthOfOldStoragePath
);
674 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, targetLocalPath
);
676 originalPathsToTriggerMediaScan
.add(child
.getStoragePath());
677 newPathsToTriggerMediaScan
.add(targetLocalPath
);
680 if (child
.getRemotePath().equals(file
.getRemotePath())) {
682 ProviderTableMeta
.FILE_PARENT
,
683 targetParent
.getFileId()
687 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
690 ProviderTableMeta
._ID
+ "=?",
691 new String
[]{String
.valueOf(child
.getFileId())}
695 } while (c
.moveToNext());
699 /// 3. apply updates in batch
701 if (getContentResolver() != null
) {
702 getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
705 getContentProviderClient().applyBatch(operations
);
708 } catch (Exception e
) {
709 Log_OC
.e(TAG
, "Fail to update " + file
.getFileId() + " and descendants in database", e
);
712 /// 4. move in local file system
713 String originalLocalPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
714 String targetLocalPath
= defaultSavePath
+ targetPath
;
715 File localFile
= new File(originalLocalPath
);
716 boolean renamed
= false
;
717 if (localFile
.exists()) {
718 File targetFile
= new File(targetLocalPath
);
719 File targetFolder
= targetFile
.getParentFile();
720 if (!targetFolder
.exists()) {
721 targetFolder
.mkdirs();
723 renamed
= localFile
.renameTo(targetFile
);
727 Iterator
<String
> it
= originalPathsToTriggerMediaScan
.iterator();
728 while (it
.hasNext()) {
729 // Notify MediaScanner about removed file
730 deleteFileInMediaScan(it
.next());
732 it
= newPathsToTriggerMediaScan
.iterator();
733 while (it
.hasNext()) {
734 // Notify MediaScanner about new file/folder
735 triggerMediaScan(it
.next());
742 public void copyLocalFile(OCFile file
, String targetPath
) {
744 if (file
!= null
&& file
.fileExists() && !OCFile
.ROOT_PATH
.equals(file
.getFileName())) {
745 String localPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
746 File localFile
= new File(localPath
);
747 boolean copied
= false
;
748 String defaultSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
749 if (localFile
.exists()) {
750 File targetFile
= new File(defaultSavePath
+ targetPath
);
751 File targetFolder
= targetFile
.getParentFile();
752 if (!targetFolder
.exists()) {
753 targetFolder
.mkdirs();
755 copied
= copyFile(localFile
, targetFile
);
757 Log_OC
.d(TAG
, "Local file COPIED : " + copied
);
761 private boolean copyFile(File src
, File target
) {
764 InputStream
in = null
;
765 OutputStream out
= null
;
768 in = new FileInputStream(src
);
769 out
= new FileOutputStream(target
);
770 byte[] buf
= new byte[1024];
772 while ((len
= in.read(buf
)) > 0) {
773 out
.write(buf
, 0, len
);
775 } catch (IOException ex
) {
778 if (in != null
) try {
780 } catch (IOException e
) {
781 e
.printStackTrace(System
.err
);
783 if (out
!= null
) try {
785 } catch (IOException e
) {
786 e
.printStackTrace(System
.err
);
794 private Vector
<OCFile
> getFolderContent(long parentId
/*, boolean onlyOnDevice*/) {
796 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
798 Uri req_uri
= Uri
.withAppendedPath(
799 ProviderTableMeta
.CONTENT_URI_DIR
,
800 String
.valueOf(parentId
));
803 if (getContentProviderClient() != null
) {
805 c
= getContentProviderClient().query(req_uri
, null
,
806 ProviderTableMeta
.FILE_PARENT
+ "=?",
807 new String
[]{String
.valueOf(parentId
)}, null
);
808 } catch (RemoteException e
) {
809 Log_OC
.e(TAG
, e
.getMessage());
813 c
= getContentResolver().query(req_uri
, null
,
814 ProviderTableMeta
.FILE_PARENT
+ "=?",
815 new String
[]{String
.valueOf(parentId
)}, null
);
818 if (c
.moveToFirst()) {
820 OCFile child
= createFileInstance(c
);
821 // TODO Enable when "On Device" is recovered ?
822 // if (child.isFolder() || !onlyOnDevice || onlyOnDevice && child.isDown()){
825 } while (c
.moveToNext());
830 Collections
.sort(ret
);
836 private OCFile
createRootDir() {
837 OCFile file
= new OCFile(OCFile
.ROOT_PATH
);
838 file
.setMimetype("DIR");
839 file
.setParentId(FileDataStorageManager
.ROOT_PARENT_ID
);
844 private boolean fileExists(String cmp_key
, String value
) {
846 if (getContentResolver() != null
) {
847 c
= getContentResolver()
848 .query(ProviderTableMeta
.CONTENT_URI
,
851 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
853 new String
[]{value
, mAccount
.name
}, null
);
856 c
= getContentProviderClient().query(
857 ProviderTableMeta
.CONTENT_URI
,
860 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
861 new String
[]{value
, mAccount
.name
}, null
);
862 } catch (RemoteException e
) {
864 "Couldn't determine file existance, assuming non existance: "
869 boolean retval
= c
.moveToFirst();
874 private Cursor
getCursorForValue(String key
, String value
) {
876 if (getContentResolver() != null
) {
877 c
= getContentResolver()
878 .query(ProviderTableMeta
.CONTENT_URI
,
881 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
883 new String
[]{value
, mAccount
.name
}, null
);
886 c
= getContentProviderClient().query(
887 ProviderTableMeta
.CONTENT_URI
,
889 key
+ "=? AND " + ProviderTableMeta
.FILE_ACCOUNT_OWNER
890 + "=?", new String
[]{value
, mAccount
.name
},
892 } catch (RemoteException e
) {
893 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
901 private OCFile
createFileInstance(Cursor c
) {
904 file
= new OCFile(c
.getString(c
905 .getColumnIndex(ProviderTableMeta
.FILE_PATH
)));
906 file
.setFileId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
907 file
.setParentId(c
.getLong(c
908 .getColumnIndex(ProviderTableMeta
.FILE_PARENT
)));
909 file
.setMimetype(c
.getString(c
910 .getColumnIndex(ProviderTableMeta
.FILE_CONTENT_TYPE
)));
911 if (!file
.isFolder()) {
912 file
.setStoragePath(c
.getString(c
913 .getColumnIndex(ProviderTableMeta
.FILE_STORAGE_PATH
)));
914 if (file
.getStoragePath() == null
) {
915 // try to find existing file and bind it with current account;
916 // with the current update of SynchronizeFolderOperation, this won't be
917 // necessary anymore after a full synchronization of the account
918 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
920 file
.setStoragePath(f
.getAbsolutePath());
921 file
.setLastSyncDateForData(f
.lastModified());
925 file
.setFileLength(c
.getLong(c
926 .getColumnIndex(ProviderTableMeta
.FILE_CONTENT_LENGTH
)));
927 file
.setCreationTimestamp(c
.getLong(c
928 .getColumnIndex(ProviderTableMeta
.FILE_CREATION
)));
929 file
.setModificationTimestamp(c
.getLong(c
930 .getColumnIndex(ProviderTableMeta
.FILE_MODIFIED
)));
931 file
.setModificationTimestampAtLastSyncForData(c
.getLong(c
932 .getColumnIndex(ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
)));
933 file
.setLastSyncDateForProperties(c
.getLong(c
934 .getColumnIndex(ProviderTableMeta
.FILE_LAST_SYNC_DATE
)));
935 file
.setLastSyncDateForData(c
.getLong(c
.
936 getColumnIndex(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
)));
937 file
.setFavorite(c
.getInt(
938 c
.getColumnIndex(ProviderTableMeta
.FILE_KEEP_IN_SYNC
)) == 1 ? true
: false
);
939 file
.setEtag(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_ETAG
)));
940 file
.setShareByLink(c
.getInt(
941 c
.getColumnIndex(ProviderTableMeta
.FILE_SHARE_BY_LINK
)) == 1 ? true
: false
);
942 file
.setPublicLink(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_PUBLIC_LINK
)));
943 file
.setPermissions(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_PERMISSIONS
)));
944 file
.setRemoteId(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_REMOTE_ID
)));
945 file
.setNeedsUpdateThumbnail(c
.getInt(
946 c
.getColumnIndex(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
)) == 1 ? true
: false
);
947 file
.setDownloading(c
.getInt(
948 c
.getColumnIndex(ProviderTableMeta
.FILE_IS_DOWNLOADING
)) == 1 ? true
: false
);
949 file
.setInConflict(c
.getInt(
950 c
.getColumnIndex(ProviderTableMeta
.FILE_IN_CONFLICT
)) == 1 ? true
: false
);
957 * Returns if the file/folder is shared by link or not
959 * @param path Path of the file/folder
962 public boolean isShareByLink(String path
) {
963 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_STORAGE_PATH
, path
);
965 if (c
.moveToFirst()) {
966 file
= createFileInstance(c
);
969 return file
.isShareByLink();
973 * Returns the public link of the file/folder
975 * @param path Path of the file/folder
978 public String
getPublicLink(String path
) {
979 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_STORAGE_PATH
, path
);
981 if (c
.moveToFirst()) {
982 file
= createFileInstance(c
);
985 return file
.getPublicLink();
989 // Methods for Shares
990 public boolean saveShare(OCShare share
) {
991 boolean overriden
= false
;
992 ContentValues cv
= new ContentValues();
993 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
994 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
995 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
996 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
997 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
998 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
999 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1000 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1001 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1003 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1004 share
.getSharedWithDisplayName()
1006 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1007 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1008 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1009 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1011 if (shareExists(share
.getIdRemoteShared())) { // for renamed files; no more delete and create
1013 if (getContentResolver() != null
) {
1014 getContentResolver().update(ProviderTableMeta
.CONTENT_URI_SHARE
, cv
,
1015 ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
1016 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
1019 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI_SHARE
,
1020 cv
, ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
1021 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
1022 } catch (RemoteException e
) {
1024 "Fail to insert insert file to database "
1029 Uri result_uri
= null
;
1030 if (getContentResolver() != null
) {
1031 result_uri
= getContentResolver().insert(
1032 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
1035 result_uri
= getContentProviderClient().insert(
1036 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
1037 } catch (RemoteException e
) {
1039 "Fail to insert insert file to database "
1043 if (result_uri
!= null
) {
1044 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
1046 share
.setId(new_id
);
1054 public OCShare
getFirstShareByPathAndType(String path
, ShareType type
) {
1056 if (getContentResolver() != null
) {
1057 c
= getContentResolver().query(
1058 ProviderTableMeta
.CONTENT_URI_SHARE
,
1060 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
1061 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
1062 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
1063 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
1067 c
= getContentProviderClient().query(
1068 ProviderTableMeta
.CONTENT_URI_SHARE
,
1070 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
1071 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
1072 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
1073 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
1076 } catch (RemoteException e
) {
1077 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
1081 OCShare share
= null
;
1082 if (c
.moveToFirst()) {
1083 share
= createShareInstance(c
);
1089 private OCShare
createShareInstance(Cursor c
) {
1090 OCShare share
= null
;
1092 share
= new OCShare(c
.getString(c
1093 .getColumnIndex(ProviderTableMeta
.OCSHARES_PATH
)));
1094 share
.setId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
1095 share
.setFileSource(c
.getLong(c
1096 .getColumnIndex(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
)));
1097 share
.setShareType(ShareType
.fromValue(c
.getInt(c
1098 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_TYPE
))));
1099 share
.setPermissions(c
.getInt(c
1100 .getColumnIndex(ProviderTableMeta
.OCSHARES_PERMISSIONS
)));
1101 share
.setSharedDate(c
.getLong(c
1102 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARED_DATE
)));
1103 share
.setExpirationDate(c
.getLong(c
1104 .getColumnIndex(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
)));
1105 share
.setToken(c
.getString(c
1106 .getColumnIndex(ProviderTableMeta
.OCSHARES_TOKEN
)));
1107 share
.setSharedWithDisplayName(c
.getString(c
1108 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
)));
1109 share
.setIsFolder(c
.getInt(
1110 c
.getColumnIndex(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
)) == 1);
1111 share
.setUserId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_USER_ID
)));
1112 share
.setIdRemoteShared(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
)));
1117 private boolean shareExists(String cmp_key
, String value
) {
1119 if (getContentResolver() != null
) {
1120 c
= getContentResolver()
1121 .query(ProviderTableMeta
.CONTENT_URI_SHARE
,
1124 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
1126 new String
[]{value
, mAccount
.name
}, null
);
1129 c
= getContentProviderClient().query(
1130 ProviderTableMeta
.CONTENT_URI_SHARE
,
1133 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
1134 new String
[]{value
, mAccount
.name
}, null
);
1135 } catch (RemoteException e
) {
1137 "Couldn't determine file existance, assuming non existance: "
1142 boolean retval
= c
.moveToFirst();
1147 private boolean shareExists(long remoteId
) {
1148 return shareExists(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, String
.valueOf(remoteId
));
1151 private void cleanSharedFiles() {
1152 ContentValues cv
= new ContentValues();
1153 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1154 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1155 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?";
1156 String
[] whereArgs
= new String
[]{mAccount
.name
};
1158 if (getContentResolver() != null
) {
1159 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1163 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1164 } catch (RemoteException e
) {
1165 Log_OC
.e(TAG
, "Exception in cleanSharedFiles" + e
.getMessage());
1170 private void cleanSharedFilesInFolder(OCFile folder
) {
1171 ContentValues cv
= new ContentValues();
1172 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1173 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1174 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1175 ProviderTableMeta
.FILE_PARENT
+ "=?";
1176 String
[] whereArgs
= new String
[] { mAccount
.name
, String
.valueOf(folder
.getFileId()) };
1178 if (getContentResolver() != null
) {
1179 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1183 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1184 } catch (RemoteException e
) {
1185 Log_OC
.e(TAG
, "Exception in cleanSharedFilesInFolder " + e
.getMessage());
1190 private void cleanShares() {
1191 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1192 String
[] whereArgs
= new String
[]{mAccount
.name
};
1194 if (getContentResolver() != null
) {
1195 getContentResolver().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1199 getContentProviderClient().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1200 } catch (RemoteException e
) {
1201 Log_OC
.e(TAG
, "Exception in cleanShares" + e
.getMessage());
1206 public void saveShares(Collection
<OCShare
> shares
) {
1208 if (shares
!= null
) {
1209 ArrayList
<ContentProviderOperation
> operations
=
1210 new ArrayList
<ContentProviderOperation
>(shares
.size());
1212 // prepare operations to insert or update files to save in the given folder
1213 for (OCShare share
: shares
) {
1214 ContentValues cv
= new ContentValues();
1215 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1216 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1217 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1218 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1219 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1220 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1221 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1222 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1223 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1225 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1226 share
.getSharedWithDisplayName()
1228 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1229 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1230 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1231 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1233 if (shareExists(share
.getIdRemoteShared())) {
1234 // updating an existing file
1236 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI_SHARE
).
1238 withSelection(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
1239 new String
[]{String
.valueOf(share
.getIdRemoteShared())})
1242 // adding a new file
1244 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1251 // apply operations in batch
1252 if (operations
.size() > 0) {
1253 @SuppressWarnings("unused")
1254 ContentProviderResult
[] results
= null
;
1255 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1256 " operations to FileContentProvider");
1258 if (getContentResolver() != null
) {
1259 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1261 results
= getContentProviderClient().applyBatch(operations
);
1264 } catch (OperationApplicationException e
) {
1265 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1267 } catch (RemoteException e
) {
1268 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1275 public void updateSharedFiles(Collection
<OCFile
> sharedFiles
) {
1278 if (sharedFiles
!= null
) {
1279 ArrayList
<ContentProviderOperation
> operations
=
1280 new ArrayList
<ContentProviderOperation
>(sharedFiles
.size());
1282 // prepare operations to insert or update files to save in the given folder
1283 for (OCFile file
: sharedFiles
) {
1284 ContentValues cv
= new ContentValues();
1285 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
1287 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
1288 file
.getModificationTimestampAtLastSyncForData()
1290 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
1291 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
1292 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
1293 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
1294 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
1295 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
1296 if (!file
.isFolder()) {
1297 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
1299 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
1300 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
1302 ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
,
1303 file
.getLastSyncDateForData()
1305 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
1306 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
1307 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
1308 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
1309 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
1310 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
1312 ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
,
1313 file
.needsUpdateThumbnail() ?
1 : 0
1316 ProviderTableMeta
.FILE_IS_DOWNLOADING
,
1317 file
.isDownloading() ?
1 : 0
1320 ProviderTableMeta
.FILE_IN_CONFLICT
,
1321 file
.isInConflict() ?
1 : 0
1324 boolean existsByPath
= fileExists(file
.getRemotePath());
1325 if (existsByPath
|| fileExists(file
.getFileId())) {
1326 // updating an existing file
1328 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
1330 withSelection(ProviderTableMeta
._ID
+ "=?",
1331 new String
[]{String
.valueOf(file
.getFileId())})
1335 // adding a new file
1337 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
1344 // apply operations in batch
1345 if (operations
.size() > 0) {
1346 @SuppressWarnings("unused")
1347 ContentProviderResult
[] results
= null
;
1348 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1349 " operations to FileContentProvider");
1351 if (getContentResolver() != null
) {
1352 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1354 results
= getContentProviderClient().applyBatch(operations
);
1357 } catch (OperationApplicationException e
) {
1358 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1360 } catch (RemoteException e
) {
1361 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1368 public void removeShare(OCShare share
) {
1369 Uri share_uri
= ProviderTableMeta
.CONTENT_URI_SHARE
;
1370 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?" + " AND " +
1371 ProviderTableMeta
.FILE_PATH
+ "=?";
1372 String
[] whereArgs
= new String
[]{mAccount
.name
, share
.getPath()};
1373 if (getContentProviderClient() != null
) {
1375 getContentProviderClient().delete(share_uri
, where
, whereArgs
);
1376 } catch (RemoteException e
) {
1377 e
.printStackTrace();
1380 getContentResolver().delete(share_uri
, where
, whereArgs
);
1384 public void saveSharesDB(ArrayList
<OCShare
> shares
) {
1387 ArrayList
<OCFile
> sharedFiles
= new ArrayList
<OCFile
>();
1389 for (OCShare share
: shares
) {
1391 String path
= share
.getPath();
1392 if (share
.isFolder()) {
1393 path
= path
+ FileUtils
.PATH_SEPARATOR
;
1396 // Update OCFile with data from share: ShareByLink and publicLink
1397 OCFile file
= getFileByPath(path
);
1399 if (share
.getShareType().equals(ShareType
.PUBLIC_LINK
)) {
1400 file
.setShareByLink(true
);
1401 sharedFiles
.add(file
);
1406 updateSharedFiles(sharedFiles
);
1410 public void saveSharesInFolder(ArrayList
<OCShare
> shares
, OCFile folder
) {
1411 cleanSharedFilesInFolder(folder
);
1412 ArrayList
<ContentProviderOperation
> operations
= new ArrayList
<ContentProviderOperation
>();
1413 operations
= prepareRemoveSharesInFolder(folder
, operations
);
1415 if (shares
!= null
) {
1416 // prepare operations to insert or update files to save in the given folder
1417 for (OCShare share
: shares
) {
1418 ContentValues cv
= new ContentValues();
1419 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1420 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1421 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1422 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1423 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1424 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1425 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1426 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1427 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1429 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1430 share
.getSharedWithDisplayName()
1432 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1433 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1434 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1435 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1438 if (shareExists(share.getIdRemoteShared())) {
1439 // updating an existing share resource
1441 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1443 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1444 new String[] { String.valueOf(share.getIdRemoteShared()) })
1449 // adding a new share resource
1451 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1459 // apply operations in batch
1460 if (operations
.size() > 0) {
1461 @SuppressWarnings("unused")
1462 ContentProviderResult
[] results
= null
;
1463 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
1465 if (getContentResolver() != null
) {
1466 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1469 results
= getContentProviderClient().applyBatch(operations
);
1472 } catch (OperationApplicationException e
) {
1473 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1475 } catch (RemoteException e
) {
1476 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1483 private ArrayList
<ContentProviderOperation
> prepareRemoveSharesInFolder(
1484 OCFile folder
, ArrayList
<ContentProviderOperation
> preparedOperations
) {
1485 if (folder
!= null
) {
1486 String where
= ProviderTableMeta
.OCSHARES_PATH
+ "=?" + " AND "
1487 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1488 String
[] whereArgs
= new String
[]{ "", mAccount
.name
};
1490 // TODO Enable when "On Device" is recovered ?
1491 Vector
<OCFile
> files
= getFolderContent(folder
/*, false*/);
1493 for (OCFile file
: files
) {
1494 whereArgs
[0] = file
.getRemotePath();
1495 preparedOperations
.add(
1496 ContentProviderOperation
.newDelete(ProviderTableMeta
.CONTENT_URI_SHARE
).
1497 withSelection(where
, whereArgs
).
1502 return preparedOperations
;
1505 if (operations.size() > 0) {
1507 if (getContentResolver() != null) {
1508 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1511 getContentProviderClient().applyBatch(operations);
1514 } catch (OperationApplicationException e) {
1515 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1517 } catch (RemoteException e) {
1518 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1524 if (getContentResolver() != null) {
1526 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE,
1531 getContentProviderClient().delete( ProviderTableMeta.CONTENT_URI_SHARE,
1535 } catch (RemoteException e) {
1536 Log_OC.e(TAG, "Exception deleting shares in a folder " + e.getMessage());
1543 public void triggerMediaScan(String path
) {
1544 Intent intent
= new Intent(Intent
.ACTION_MEDIA_SCANNER_SCAN_FILE
);
1545 intent
.setData(Uri
.fromFile(new File(path
)));
1546 MainApp
.getAppContext().sendBroadcast(intent
);
1549 public void deleteFileInMediaScan(String path
) {
1551 String mimetypeString
= FileStorageUtils
.getMimeTypeFromName(path
);
1552 ContentResolver contentResolver
= getContentResolver();
1554 if (contentResolver
!= null
) {
1555 if (mimetypeString
.startsWith("image/")) {
1557 contentResolver
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1558 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1559 } else if (mimetypeString
.startsWith("audio/")) {
1561 contentResolver
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1562 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1563 } else if (mimetypeString
.startsWith("video/")) {
1565 contentResolver
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1566 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1569 ContentProviderClient contentProviderClient
= getContentProviderClient();
1571 if (mimetypeString
.startsWith("image/")) {
1573 contentProviderClient
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1574 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1575 } else if (mimetypeString
.startsWith("audio/")) {
1577 contentProviderClient
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1578 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1579 } else if (mimetypeString
.startsWith("video/")) {
1581 contentProviderClient
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1582 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1584 } catch (RemoteException e
) {
1585 Log_OC
.e(TAG
, "Exception deleting media file in MediaStore " + e
.getMessage());
1591 public void saveConflict(OCFile file
, boolean inConflict
) {
1592 ContentValues cv
= new ContentValues();
1593 cv
.put(ProviderTableMeta
.FILE_IN_CONFLICT
, inConflict
);
1595 if (getContentResolver() != null
) {
1596 updated
= getContentResolver().update(
1597 ProviderTableMeta
.CONTENT_URI_FILE
,
1599 ProviderTableMeta
._ID
+ "=?",
1600 new String
[] { String
.valueOf(file
.getFileId())}
1604 updated
= getContentProviderClient().update(
1605 ProviderTableMeta
.CONTENT_URI_FILE
,
1607 ProviderTableMeta
._ID
+ "=?",
1608 new String
[]{String
.valueOf(file
.getFileId())}
1610 } catch (RemoteException e
) {
1611 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1615 Log_OC
.d(TAG
, "Number of files updated with CONFLICT: " + updated
);
1619 /// set conflict in all ancestor folders
1621 long parentId
= file
.getParentId();
1622 Set
<String
> ancestorIds
= new HashSet
<String
>();
1623 while (parentId
!= FileDataStorageManager
.ROOT_PARENT_ID
) {
1624 ancestorIds
.add(Long
.toString(parentId
));
1625 parentId
= getFileById(parentId
).getParentId();
1628 if (ancestorIds
.size() > 0) {
1629 StringBuffer whereBuffer
= new StringBuffer();
1630 whereBuffer
.append(ProviderTableMeta
._ID
).append(" IN (");
1631 for (int i
= 0; i
< ancestorIds
.size() - 1; i
++) {
1632 whereBuffer
.append("?,");
1634 whereBuffer
.append("?");
1635 whereBuffer
.append(")");
1637 if (getContentResolver() != null
) {
1638 updated
= getContentResolver().update(
1639 ProviderTableMeta
.CONTENT_URI_FILE
,
1641 whereBuffer
.toString(),
1642 ancestorIds
.toArray(new String
[]{})
1646 updated
= getContentProviderClient().update(
1647 ProviderTableMeta
.CONTENT_URI_FILE
,
1649 whereBuffer
.toString(),
1650 ancestorIds
.toArray(new String
[]{})
1652 } catch (RemoteException e
) {
1653 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1656 } // else file is ROOT folder, no parent to set in conflict
1659 /// TODO update conflict in ancestor folders
1660 // (not directly unset; maybe there are more conflicts below them)
1664 Log_OC
.d(TAG
, "Number of parents updated with CONFLICT: " + updated
);