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 ContentResolver
getContentResolver() {
94 return mContentResolver
;
97 public ContentProviderClient
getContentProviderClient() {
98 return mContentProviderClient
;
102 public OCFile
getFileByPath(String path
) {
103 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_PATH
, path
);
105 if (c
.moveToFirst()) {
106 file
= createFileInstance(c
);
109 if (file
== null
&& OCFile
.ROOT_PATH
.equals(path
)) {
110 return createRootDir(); // root should always exist
116 public OCFile
getFileById(long id
) {
117 Cursor c
= getCursorForValue(ProviderTableMeta
._ID
, String
.valueOf(id
));
119 if (c
.moveToFirst()) {
120 file
= createFileInstance(c
);
126 public OCFile
getFileByLocalPath(String path
) {
127 Cursor c
= getCursorForValue(ProviderTableMeta
.FILE_STORAGE_PATH
, path
);
129 if (c
.moveToFirst()) {
130 file
= createFileInstance(c
);
136 public boolean fileExists(long id
) {
137 return fileExists(ProviderTableMeta
._ID
, String
.valueOf(id
));
140 public boolean fileExists(String path
) {
141 return fileExists(ProviderTableMeta
.FILE_PATH
, path
);
145 public Vector
<OCFile
> getFolderContent(OCFile f
/*, boolean onlyOnDevice*/) {
146 if (f
!= null
&& f
.isFolder() && f
.getFileId() != -1) {
147 // TODO Enable when "On Device" is recovered ?
148 return getFolderContent(f
.getFileId()/*, onlyOnDevice*/);
151 return new Vector
<OCFile
>();
156 public Vector
<OCFile
> getFolderImages(OCFile folder
/*, boolean onlyOnDevice*/) {
157 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
158 if (folder
!= null
) {
159 // TODO better implementation, filtering in the access to database instead of here
160 // TODO Enable when "On Device" is recovered ?
161 Vector
<OCFile
> tmp
= getFolderContent(folder
/*, onlyOnDevice*/);
162 OCFile current
= null
;
163 for (int i
=0; i
<tmp
.size(); i
++) {
164 current
= tmp
.get(i
);
165 if (current
.isImage()) {
173 public boolean saveFile(OCFile file
) {
174 boolean overriden
= false
;
175 ContentValues cv
= new ContentValues();
176 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
178 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
179 file
.getModificationTimestampAtLastSyncForData()
181 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
182 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
183 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
184 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
185 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
186 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
187 if (!file
.isFolder())
188 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
189 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
190 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
191 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, file
.getLastSyncDateForData());
192 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
193 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
194 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
195 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
196 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
197 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
198 cv
.put(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
, file
.needsUpdateThumbnail());
199 cv
.put(ProviderTableMeta
.FILE_IS_DOWNLOADING
, file
.isDownloading());
200 cv
.put(ProviderTableMeta
.FILE_IN_CONFLICT
, file
.isInConflict());
202 boolean sameRemotePath
= fileExists(file
.getRemotePath());
203 if (sameRemotePath
|| fileExists(file
.getFileId())) { // for renamed files; no more delete and create
206 if (sameRemotePath
) {
207 oldFile
= getFileByPath(file
.getRemotePath());
208 file
.setFileId(oldFile
.getFileId());
210 oldFile
= getFileById(file
.getFileId());
214 if (getContentResolver() != null
) {
215 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
,
216 ProviderTableMeta
._ID
+ "=?",
217 new String
[]{String
.valueOf(file
.getFileId())});
220 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
,
221 cv
, ProviderTableMeta
._ID
+ "=?",
222 new String
[]{String
.valueOf(file
.getFileId())});
223 } catch (RemoteException e
) {
225 "Fail to insert insert file to database "
230 Uri result_uri
= null
;
231 if (getContentResolver() != null
) {
232 result_uri
= getContentResolver().insert(
233 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
236 result_uri
= getContentProviderClient().insert(
237 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
238 } catch (RemoteException e
) {
240 "Fail to insert insert file to database "
244 if (result_uri
!= null
) {
245 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
247 file
.setFileId(new_id
);
256 * Inserts or updates the list of files contained in a given folder.
258 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
259 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
262 * @param updatedFiles
263 * @param filesToRemove
265 public void saveFolder(
266 OCFile folder
, Collection
<OCFile
> updatedFiles
, Collection
<OCFile
> filesToRemove
269 Log_OC
.d(TAG
, "Saving folder " + folder
.getRemotePath() + " with " + updatedFiles
.size()
270 + " children and " + filesToRemove
.size() + " files to remove");
272 ArrayList
<ContentProviderOperation
> operations
=
273 new ArrayList
<ContentProviderOperation
>(updatedFiles
.size());
275 // prepare operations to insert or update files to save in the given folder
276 for (OCFile file
: updatedFiles
) {
277 ContentValues cv
= new ContentValues();
278 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
280 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
281 file
.getModificationTimestampAtLastSyncForData()
283 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
284 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
285 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
286 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
287 //cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
288 cv
.put(ProviderTableMeta
.FILE_PARENT
, folder
.getFileId());
289 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
290 if (!file
.isFolder()) {
291 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
293 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
294 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
295 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, file
.getLastSyncDateForData());
296 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
297 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
298 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
299 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
300 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
301 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
302 cv
.put(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
, file
.needsUpdateThumbnail());
303 cv
.put(ProviderTableMeta
.FILE_IS_DOWNLOADING
, file
.isDownloading());
304 cv
.put(ProviderTableMeta
.FILE_IN_CONFLICT
, file
.isInConflict());
306 boolean existsByPath
= fileExists(file
.getRemotePath());
307 if (existsByPath
|| fileExists(file
.getFileId())) {
308 // updating an existing file
309 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
311 withSelection(ProviderTableMeta
._ID
+ "=?",
312 new String
[]{String
.valueOf(file
.getFileId())})
317 operations
.add(ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
318 withValues(cv
).build());
322 // prepare operations to remove files in the given folder
323 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " +
324 ProviderTableMeta
.FILE_PATH
+ "=?";
325 String
[] whereArgs
= null
;
326 for (OCFile file
: filesToRemove
) {
327 if (file
.getParentId() == folder
.getFileId()) {
328 whereArgs
= new String
[]{mAccount
.name
, file
.getRemotePath()};
329 if (file
.isFolder()) {
330 operations
.add(ContentProviderOperation
.newDelete(
331 ContentUris
.withAppendedId(
332 ProviderTableMeta
.CONTENT_URI_DIR
, file
.getFileId()
334 ).withSelection(where
, whereArgs
).build());
337 new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
338 if (localFolder
.exists()) {
339 removeLocalFolder(localFolder
);
342 operations
.add(ContentProviderOperation
.newDelete(
343 ContentUris
.withAppendedId(
344 ProviderTableMeta
.CONTENT_URI_FILE
, file
.getFileId()
346 ).withSelection(where
, whereArgs
).build());
349 String path
= file
.getStoragePath();
350 new File(path
).delete();
351 triggerMediaScan(path
); // notify MediaScanner about removed file
357 // update metadata of folder
358 ContentValues cv
= new ContentValues();
359 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, folder
.getModificationTimestamp());
361 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
362 folder
.getModificationTimestampAtLastSyncForData()
364 cv
.put(ProviderTableMeta
.FILE_CREATION
, folder
.getCreationTimestamp());
365 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, 0);
366 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, folder
.getMimetype());
367 cv
.put(ProviderTableMeta
.FILE_NAME
, folder
.getFileName());
368 cv
.put(ProviderTableMeta
.FILE_PARENT
, folder
.getParentId());
369 cv
.put(ProviderTableMeta
.FILE_PATH
, folder
.getRemotePath());
370 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
371 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, folder
.getLastSyncDateForProperties());
372 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, folder
.getLastSyncDateForData());
373 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, folder
.isFavorite() ?
1 : 0);
374 cv
.put(ProviderTableMeta
.FILE_ETAG
, folder
.getEtag());
375 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, folder
.isShareByLink() ?
1 : 0);
376 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, folder
.getPublicLink());
377 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, folder
.getPermissions());
378 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, folder
.getRemoteId());
380 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
382 withSelection(ProviderTableMeta
._ID
+ "=?",
383 new String
[]{String
.valueOf(folder
.getFileId())})
386 // apply operations in batch
387 ContentProviderResult
[] results
= null
;
388 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
390 if (getContentResolver() != null
) {
391 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
394 results
= getContentProviderClient().applyBatch(operations
);
397 } catch (OperationApplicationException e
) {
398 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
400 } catch (RemoteException e
) {
401 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
404 // update new id in file objects for insertions
405 if (results
!= null
) {
407 Iterator
<OCFile
> filesIt
= updatedFiles
.iterator();
409 for (int i
= 0; i
< results
.length
; i
++) {
410 if (filesIt
.hasNext()) {
411 file
= filesIt
.next();
415 if (results
[i
].uri
!= null
) {
416 newId
= Long
.parseLong(results
[i
].uri
.getPathSegments().get(1));
417 //updatedFiles.get(i).setFileId(newId);
419 file
.setFileId(newId
);
428 public boolean removeFile(OCFile file
, boolean removeDBData
, boolean removeLocalCopy
) {
429 boolean success
= true
;
431 if (file
.isFolder()) {
432 success
= removeFolder(file
, removeDBData
, removeLocalCopy
);
436 //Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
437 Uri file_uri
= ContentUris
.withAppendedId(ProviderTableMeta
.CONTENT_URI_FILE
, file
.getFileId());
438 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " + ProviderTableMeta
.FILE_PATH
+ "=?";
439 String
[] whereArgs
= new String
[]{mAccount
.name
, file
.getRemotePath()};
441 if (getContentProviderClient() != null
) {
443 deleted
= getContentProviderClient().delete(file_uri
, where
, whereArgs
);
444 } catch (RemoteException e
) {
448 deleted
= getContentResolver().delete(file_uri
, where
, whereArgs
);
450 success
&= (deleted
> 0);
452 String localPath
= file
.getStoragePath();
453 if (removeLocalCopy
&& file
.isDown() && localPath
!= null
&& success
) {
454 success
= new File(localPath
).delete();
456 deleteFileInMediaScan(localPath
);
458 if (!removeDBData
&& success
) {
459 // maybe unnecessary, but should be checked TODO remove if unnecessary
460 file
.setStoragePath(null
);
462 saveConflict(file
, false
);
471 public boolean removeFolder(OCFile folder
, boolean removeDBData
, boolean removeLocalContent
) {
472 boolean success
= true
;
473 if (folder
!= null
&& folder
.isFolder()) {
474 if (removeDBData
&& folder
.getFileId() != -1) {
475 success
= removeFolderInDb(folder
);
477 if (removeLocalContent
&& success
) {
478 success
= removeLocalFolder(folder
);
484 private boolean removeFolderInDb(OCFile folder
) {
485 Uri folder_uri
= Uri
.withAppendedPath(ProviderTableMeta
.CONTENT_URI_DIR
, "" +
486 folder
.getFileId()); // URI for recursive deletion
487 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " +
488 ProviderTableMeta
.FILE_PATH
+ "=?";
489 String
[] whereArgs
= new String
[]{mAccount
.name
, folder
.getRemotePath()};
491 if (getContentProviderClient() != null
) {
493 deleted
= getContentProviderClient().delete(folder_uri
, where
, whereArgs
);
494 } catch (RemoteException e
) {
498 deleted
= getContentResolver().delete(folder_uri
, where
, whereArgs
);
503 private boolean removeLocalFolder(OCFile folder
) {
504 boolean success
= true
;
505 String localFolderPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, folder
);
506 File localFolder
= new File(localFolderPath
);
507 if (localFolder
.exists()) {
508 // stage 1: remove the local files already registered in the files database
509 // TODO Enable when "On Device" is recovered ?
510 Vector
<OCFile
> files
= getFolderContent(folder
.getFileId()/*, false*/);
512 for (OCFile file
: files
) {
513 if (file
.isFolder()) {
514 success
&= removeLocalFolder(file
);
517 File localFile
= new File(file
.getStoragePath());
518 success
&= localFile
.delete();
520 // notify MediaScanner about removed file
521 deleteFileInMediaScan(file
.getStoragePath());
522 file
.setStoragePath(null
);
530 // stage 2: remove the folder itself and any local file inside out of sync;
531 // for instance, after clearing the app cache or reinstalling
532 success
&= removeLocalFolder(localFolder
);
537 private boolean removeLocalFolder(File localFolder
) {
538 boolean success
= true
;
539 File
[] localFiles
= localFolder
.listFiles();
540 if (localFiles
!= null
) {
541 for (File localFile
: localFiles
) {
542 if (localFile
.isDirectory()) {
543 success
&= removeLocalFolder(localFile
);
545 String path
= localFile
.getAbsolutePath();
546 success
&= localFile
.delete();
550 success
&= localFolder
.delete();
556 * Updates database and file system for a file or folder that was moved to a different location.
558 * TODO explore better (faster) implementations
559 * TODO throw exceptions up !
561 public void moveLocalFile(OCFile file
, String targetPath
, String targetParentPath
) {
563 if (file
!= null
&& file
.fileExists() && !OCFile
.ROOT_PATH
.equals(file
.getFileName())) {
565 OCFile targetParent
= getFileByPath(targetParentPath
);
566 if (targetParent
== null
) {
567 throw new IllegalStateException("Parent folder of the target path does not exist!!");
570 /// 1. get all the descendants of the moved element in a single QUERY
572 if (getContentProviderClient() != null
) {
574 c
= getContentProviderClient().query(
575 ProviderTableMeta
.CONTENT_URI
,
577 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
578 ProviderTableMeta
.FILE_PATH
+ " LIKE ? ",
581 file
.getRemotePath() + "%"
583 ProviderTableMeta
.FILE_PATH
+ " ASC "
585 } catch (RemoteException e
) {
586 Log_OC
.e(TAG
, e
.getMessage());
590 c
= getContentResolver().query(
591 ProviderTableMeta
.CONTENT_URI
,
593 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
594 ProviderTableMeta
.FILE_PATH
+ " LIKE ? ",
597 file
.getRemotePath() + "%"
599 ProviderTableMeta
.FILE_PATH
+ " ASC "
603 /// 2. prepare a batch of update operations to change all the descendants
604 ArrayList
<ContentProviderOperation
> operations
=
605 new ArrayList
<ContentProviderOperation
>(c
.getCount());
606 String defaultSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
607 List
<String
> originalPathsToTriggerMediaScan
= new ArrayList
<String
>();
608 List
<String
> newPathsToTriggerMediaScan
= new ArrayList
<String
>();
609 if (c
.moveToFirst()) {
610 int lengthOfOldPath
= file
.getRemotePath().length();
611 int lengthOfOldStoragePath
= defaultSavePath
.length() + lengthOfOldPath
;
613 ContentValues cv
= new ContentValues(); // keep construction in the loop
614 OCFile child
= createFileInstance(c
);
616 ProviderTableMeta
.FILE_PATH
,
617 targetPath
+ child
.getRemotePath().substring(lengthOfOldPath
)
619 if (child
.getStoragePath() != null
&&
620 child
.getStoragePath().startsWith(defaultSavePath
)) {
621 // update link to downloaded content - but local move is not done here!
622 String targetLocalPath
= defaultSavePath
+ targetPath
+
623 child
.getStoragePath().substring(lengthOfOldStoragePath
);
625 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, targetLocalPath
);
627 originalPathsToTriggerMediaScan
.add(child
.getStoragePath());
628 newPathsToTriggerMediaScan
.add(targetLocalPath
);
631 if (child
.getRemotePath().equals(file
.getRemotePath())) {
633 ProviderTableMeta
.FILE_PARENT
,
634 targetParent
.getFileId()
638 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
641 ProviderTableMeta
._ID
+ "=?",
642 new String
[]{String
.valueOf(child
.getFileId())}
646 } while (c
.moveToNext());
650 /// 3. apply updates in batch
652 if (getContentResolver() != null
) {
653 getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
656 getContentProviderClient().applyBatch(operations
);
659 } catch (Exception e
) {
660 Log_OC
.e(TAG
, "Fail to update " + file
.getFileId() + " and descendants in database", e
);
663 /// 4. move in local file system
664 String originalLocalPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
665 String targetLocalPath
= defaultSavePath
+ targetPath
;
666 File localFile
= new File(originalLocalPath
);
667 boolean renamed
= false
;
668 if (localFile
.exists()) {
669 File targetFile
= new File(targetLocalPath
);
670 File targetFolder
= targetFile
.getParentFile();
671 if (!targetFolder
.exists()) {
672 targetFolder
.mkdirs();
674 renamed
= localFile
.renameTo(targetFile
);
678 Iterator
<String
> it
= originalPathsToTriggerMediaScan
.iterator();
679 while (it
.hasNext()) {
680 // Notify MediaScanner about removed file
681 deleteFileInMediaScan(it
.next());
683 it
= newPathsToTriggerMediaScan
.iterator();
684 while (it
.hasNext()) {
685 // Notify MediaScanner about new file/folder
686 triggerMediaScan(it
.next());
693 public void copyLocalFile(OCFile file
, String targetPath
) {
695 if (file
!= null
&& file
.fileExists() && !OCFile
.ROOT_PATH
.equals(file
.getFileName())) {
696 String localPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
697 File localFile
= new File(localPath
);
698 boolean copied
= false
;
699 String defaultSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
700 if (localFile
.exists()) {
701 File targetFile
= new File(defaultSavePath
+ targetPath
);
702 File targetFolder
= targetFile
.getParentFile();
703 if (!targetFolder
.exists()) {
704 targetFolder
.mkdirs();
706 copied
= copyFile(localFile
, targetFile
);
708 Log_OC
.d(TAG
, "Local file COPIED : " + copied
);
712 private boolean copyFile(File src
, File target
) {
715 InputStream
in = null
;
716 OutputStream out
= null
;
719 in = new FileInputStream(src
);
720 out
= new FileOutputStream(target
);
721 byte[] buf
= new byte[1024];
723 while ((len
= in.read(buf
)) > 0) {
724 out
.write(buf
, 0, len
);
726 } catch (IOException ex
) {
729 if (in != null
) try {
731 } catch (IOException e
) {
732 e
.printStackTrace(System
.err
);
734 if (out
!= null
) try {
736 } catch (IOException e
) {
737 e
.printStackTrace(System
.err
);
745 private Vector
<OCFile
> getFolderContent(long parentId
/*, boolean onlyOnDevice*/) {
747 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
749 Uri req_uri
= Uri
.withAppendedPath(
750 ProviderTableMeta
.CONTENT_URI_DIR
,
751 String
.valueOf(parentId
));
754 if (getContentProviderClient() != null
) {
756 c
= getContentProviderClient().query(req_uri
, null
,
757 ProviderTableMeta
.FILE_PARENT
+ "=?",
758 new String
[]{String
.valueOf(parentId
)}, null
);
759 } catch (RemoteException e
) {
760 Log_OC
.e(TAG
, e
.getMessage());
764 c
= getContentResolver().query(req_uri
, null
,
765 ProviderTableMeta
.FILE_PARENT
+ "=?",
766 new String
[]{String
.valueOf(parentId
)}, null
);
769 if (c
.moveToFirst()) {
771 OCFile child
= createFileInstance(c
);
772 // TODO Enable when "On Device" is recovered ?
773 // if (child.isFolder() || !onlyOnDevice || onlyOnDevice && child.isDown()){
776 } while (c
.moveToNext());
781 Collections
.sort(ret
);
787 private OCFile
createRootDir() {
788 OCFile file
= new OCFile(OCFile
.ROOT_PATH
);
789 file
.setMimetype("DIR");
790 file
.setParentId(FileDataStorageManager
.ROOT_PARENT_ID
);
795 private boolean fileExists(String cmp_key
, String value
) {
797 if (getContentResolver() != null
) {
798 c
= getContentResolver()
799 .query(ProviderTableMeta
.CONTENT_URI
,
802 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
804 new String
[]{value
, mAccount
.name
}, null
);
807 c
= getContentProviderClient().query(
808 ProviderTableMeta
.CONTENT_URI
,
811 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
812 new String
[]{value
, mAccount
.name
}, null
);
813 } catch (RemoteException e
) {
815 "Couldn't determine file existance, assuming non existance: "
820 boolean retval
= c
.moveToFirst();
825 private Cursor
getCursorForValue(String key
, String value
) {
827 if (getContentResolver() != null
) {
828 c
= getContentResolver()
829 .query(ProviderTableMeta
.CONTENT_URI
,
832 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
834 new String
[]{value
, mAccount
.name
}, null
);
837 c
= getContentProviderClient().query(
838 ProviderTableMeta
.CONTENT_URI
,
840 key
+ "=? AND " + ProviderTableMeta
.FILE_ACCOUNT_OWNER
841 + "=?", new String
[]{value
, mAccount
.name
},
843 } catch (RemoteException e
) {
844 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
852 private OCFile
createFileInstance(Cursor c
) {
855 file
= new OCFile(c
.getString(c
856 .getColumnIndex(ProviderTableMeta
.FILE_PATH
)));
857 file
.setFileId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
858 file
.setParentId(c
.getLong(c
859 .getColumnIndex(ProviderTableMeta
.FILE_PARENT
)));
860 file
.setMimetype(c
.getString(c
861 .getColumnIndex(ProviderTableMeta
.FILE_CONTENT_TYPE
)));
862 if (!file
.isFolder()) {
863 file
.setStoragePath(c
.getString(c
864 .getColumnIndex(ProviderTableMeta
.FILE_STORAGE_PATH
)));
865 if (file
.getStoragePath() == null
) {
866 // try to find existing file and bind it with current account;
867 // with the current update of SynchronizeFolderOperation, this won't be
868 // necessary anymore after a full synchronization of the account
869 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
871 file
.setStoragePath(f
.getAbsolutePath());
872 file
.setLastSyncDateForData(f
.lastModified());
876 file
.setFileLength(c
.getLong(c
877 .getColumnIndex(ProviderTableMeta
.FILE_CONTENT_LENGTH
)));
878 file
.setCreationTimestamp(c
.getLong(c
879 .getColumnIndex(ProviderTableMeta
.FILE_CREATION
)));
880 file
.setModificationTimestamp(c
.getLong(c
881 .getColumnIndex(ProviderTableMeta
.FILE_MODIFIED
)));
882 file
.setModificationTimestampAtLastSyncForData(c
.getLong(c
883 .getColumnIndex(ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
)));
884 file
.setLastSyncDateForProperties(c
.getLong(c
885 .getColumnIndex(ProviderTableMeta
.FILE_LAST_SYNC_DATE
)));
886 file
.setLastSyncDateForData(c
.getLong(c
.
887 getColumnIndex(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
)));
888 file
.setFavorite(c
.getInt(
889 c
.getColumnIndex(ProviderTableMeta
.FILE_KEEP_IN_SYNC
)) == 1 ? true
: false
);
890 file
.setEtag(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_ETAG
)));
891 file
.setShareByLink(c
.getInt(
892 c
.getColumnIndex(ProviderTableMeta
.FILE_SHARE_BY_LINK
)) == 1 ? true
: false
);
893 file
.setPublicLink(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_PUBLIC_LINK
)));
894 file
.setPermissions(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_PERMISSIONS
)));
895 file
.setRemoteId(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_REMOTE_ID
)));
896 file
.setNeedsUpdateThumbnail(c
.getInt(
897 c
.getColumnIndex(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
)) == 1 ? true
: false
);
898 file
.setDownloading(c
.getInt(
899 c
.getColumnIndex(ProviderTableMeta
.FILE_IS_DOWNLOADING
)) == 1 ? true
: false
);
900 file
.setInConflict(c
.getInt(
901 c
.getColumnIndex(ProviderTableMeta
.FILE_IN_CONFLICT
)) == 1 ? true
: false
);
907 // Methods for Shares
908 public boolean saveShare(OCShare share
) {
909 boolean overriden
= false
;
910 ContentValues cv
= new ContentValues();
911 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
912 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
913 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
914 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
915 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
916 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
917 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
918 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
919 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
921 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
922 share
.getSharedWithDisplayName()
924 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
925 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
926 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
927 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
929 if (shareExists(share
.getIdRemoteShared())) { // for renamed files; no more delete and create
931 if (getContentResolver() != null
) {
932 getContentResolver().update(ProviderTableMeta
.CONTENT_URI_SHARE
, cv
,
933 ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
934 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
937 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI_SHARE
,
938 cv
, ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
939 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
940 } catch (RemoteException e
) {
942 "Fail to insert insert file to database "
947 Uri result_uri
= null
;
948 if (getContentResolver() != null
) {
949 result_uri
= getContentResolver().insert(
950 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
953 result_uri
= getContentProviderClient().insert(
954 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
955 } catch (RemoteException e
) {
957 "Fail to insert insert file to database "
961 if (result_uri
!= null
) {
962 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
972 public OCShare
getFirstShareByPathAndType(String path
, ShareType type
) {
974 if (getContentResolver() != null
) {
975 c
= getContentResolver().query(
976 ProviderTableMeta
.CONTENT_URI_SHARE
,
978 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
979 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
980 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
981 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
985 c
= getContentProviderClient().query(
986 ProviderTableMeta
.CONTENT_URI_SHARE
,
988 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
989 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
990 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
991 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
994 } catch (RemoteException e
) {
995 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
999 OCShare share
= null
;
1000 if (c
.moveToFirst()) {
1001 share
= createShareInstance(c
);
1007 private OCShare
createShareInstance(Cursor c
) {
1008 OCShare share
= null
;
1010 share
= new OCShare(c
.getString(c
1011 .getColumnIndex(ProviderTableMeta
.OCSHARES_PATH
)));
1012 share
.setId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
1013 share
.setFileSource(c
.getLong(c
1014 .getColumnIndex(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
)));
1015 share
.setShareType(ShareType
.fromValue(c
.getInt(c
1016 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_TYPE
))));
1017 share
.setPermissions(c
.getInt(c
1018 .getColumnIndex(ProviderTableMeta
.OCSHARES_PERMISSIONS
)));
1019 share
.setSharedDate(c
.getLong(c
1020 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARED_DATE
)));
1021 share
.setExpirationDate(c
.getLong(c
1022 .getColumnIndex(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
)));
1023 share
.setToken(c
.getString(c
1024 .getColumnIndex(ProviderTableMeta
.OCSHARES_TOKEN
)));
1025 share
.setSharedWithDisplayName(c
.getString(c
1026 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
)));
1027 share
.setIsFolder(c
.getInt(
1028 c
.getColumnIndex(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
)) == 1);
1029 share
.setUserId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_USER_ID
)));
1030 share
.setIdRemoteShared(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
)));
1035 private boolean shareExists(String cmp_key
, String value
) {
1037 if (getContentResolver() != null
) {
1038 c
= getContentResolver()
1039 .query(ProviderTableMeta
.CONTENT_URI_SHARE
,
1042 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
1044 new String
[]{value
, mAccount
.name
}, null
);
1047 c
= getContentProviderClient().query(
1048 ProviderTableMeta
.CONTENT_URI_SHARE
,
1051 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
1052 new String
[]{value
, mAccount
.name
}, null
);
1053 } catch (RemoteException e
) {
1055 "Couldn't determine file existance, assuming non existance: "
1060 boolean retval
= c
.moveToFirst();
1065 private boolean shareExists(long remoteId
) {
1066 return shareExists(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, String
.valueOf(remoteId
));
1069 private void cleanSharedFiles() {
1070 ContentValues cv
= new ContentValues();
1071 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1072 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1073 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?";
1074 String
[] whereArgs
= new String
[]{mAccount
.name
};
1076 if (getContentResolver() != null
) {
1077 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1081 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1082 } catch (RemoteException e
) {
1083 Log_OC
.e(TAG
, "Exception in cleanSharedFiles" + e
.getMessage());
1088 private void cleanSharedFilesInFolder(OCFile folder
) {
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
+ "=? AND " +
1093 ProviderTableMeta
.FILE_PARENT
+ "=?";
1094 String
[] whereArgs
= new String
[] { mAccount
.name
, String
.valueOf(folder
.getFileId()) };
1096 if (getContentResolver() != null
) {
1097 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1101 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1102 } catch (RemoteException e
) {
1103 Log_OC
.e(TAG
, "Exception in cleanSharedFilesInFolder " + e
.getMessage());
1108 private void cleanShares() {
1109 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1110 String
[] whereArgs
= new String
[]{mAccount
.name
};
1112 if (getContentResolver() != null
) {
1113 getContentResolver().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1117 getContentProviderClient().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1118 } catch (RemoteException e
) {
1119 Log_OC
.e(TAG
, "Exception in cleanShares" + e
.getMessage());
1124 public void saveShares(Collection
<OCShare
> shares
) {
1126 if (shares
!= null
) {
1127 ArrayList
<ContentProviderOperation
> operations
=
1128 new ArrayList
<ContentProviderOperation
>(shares
.size());
1130 // prepare operations to insert or update files to save in the given folder
1131 for (OCShare share
: shares
) {
1132 ContentValues cv
= new ContentValues();
1133 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1134 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1135 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1136 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1137 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1138 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1139 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1140 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1141 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1143 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1144 share
.getSharedWithDisplayName()
1146 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1147 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1148 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1149 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1151 if (shareExists(share
.getIdRemoteShared())) {
1152 // updating an existing file
1154 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI_SHARE
).
1156 withSelection(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
1157 new String
[]{String
.valueOf(share
.getIdRemoteShared())})
1160 // adding a new file
1162 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1169 // apply operations in batch
1170 if (operations
.size() > 0) {
1171 @SuppressWarnings("unused")
1172 ContentProviderResult
[] results
= null
;
1173 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1174 " operations to FileContentProvider");
1176 if (getContentResolver() != null
) {
1177 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1179 results
= getContentProviderClient().applyBatch(operations
);
1182 } catch (OperationApplicationException e
) {
1183 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1185 } catch (RemoteException e
) {
1186 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1193 public void updateSharedFiles(Collection
<OCFile
> sharedFiles
) {
1196 if (sharedFiles
!= null
) {
1197 ArrayList
<ContentProviderOperation
> operations
=
1198 new ArrayList
<ContentProviderOperation
>(sharedFiles
.size());
1200 // prepare operations to insert or update files to save in the given folder
1201 for (OCFile file
: sharedFiles
) {
1202 ContentValues cv
= new ContentValues();
1203 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
1205 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
1206 file
.getModificationTimestampAtLastSyncForData()
1208 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
1209 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
1210 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
1211 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
1212 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
1213 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
1214 if (!file
.isFolder()) {
1215 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
1217 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
1218 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
1220 ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
,
1221 file
.getLastSyncDateForData()
1223 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
1224 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
1225 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
1226 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
1227 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
1228 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
1230 ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
,
1231 file
.needsUpdateThumbnail() ?
1 : 0
1234 ProviderTableMeta
.FILE_IS_DOWNLOADING
,
1235 file
.isDownloading() ?
1 : 0
1238 ProviderTableMeta
.FILE_IN_CONFLICT
,
1239 file
.isInConflict() ?
1 : 0
1242 boolean existsByPath
= fileExists(file
.getRemotePath());
1243 if (existsByPath
|| fileExists(file
.getFileId())) {
1244 // updating an existing file
1246 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
1248 withSelection(ProviderTableMeta
._ID
+ "=?",
1249 new String
[]{String
.valueOf(file
.getFileId())})
1253 // adding a new file
1255 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
1262 // apply operations in batch
1263 if (operations
.size() > 0) {
1264 @SuppressWarnings("unused")
1265 ContentProviderResult
[] results
= null
;
1266 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1267 " operations to FileContentProvider");
1269 if (getContentResolver() != null
) {
1270 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1272 results
= getContentProviderClient().applyBatch(operations
);
1275 } catch (OperationApplicationException e
) {
1276 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1278 } catch (RemoteException e
) {
1279 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1286 public void removeShare(OCShare share
) {
1287 Uri share_uri
= ProviderTableMeta
.CONTENT_URI_SHARE
;
1288 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?" + " AND " +
1289 ProviderTableMeta
.FILE_PATH
+ "=?";
1290 String
[] whereArgs
= new String
[]{mAccount
.name
, share
.getPath()};
1291 if (getContentProviderClient() != null
) {
1293 getContentProviderClient().delete(share_uri
, where
, whereArgs
);
1294 } catch (RemoteException e
) {
1295 e
.printStackTrace();
1298 getContentResolver().delete(share_uri
, where
, whereArgs
);
1302 public void saveSharesDB(ArrayList
<OCShare
> shares
) {
1305 ArrayList
<OCFile
> sharedFiles
= new ArrayList
<OCFile
>();
1307 for (OCShare share
: shares
) {
1309 String path
= share
.getPath();
1310 if (share
.isFolder()) {
1311 path
= path
+ FileUtils
.PATH_SEPARATOR
;
1314 // Update OCFile with data from share: ShareByLink and publicLink
1315 OCFile file
= getFileByPath(path
);
1317 if (share
.getShareType().equals(ShareType
.PUBLIC_LINK
)) {
1318 file
.setShareByLink(true
);
1319 sharedFiles
.add(file
);
1324 updateSharedFiles(sharedFiles
);
1328 public void saveSharesInFolder(ArrayList
<OCShare
> shares
, OCFile folder
) {
1329 cleanSharedFilesInFolder(folder
);
1330 ArrayList
<ContentProviderOperation
> operations
= new ArrayList
<ContentProviderOperation
>();
1331 operations
= prepareRemoveSharesInFolder(folder
, operations
);
1333 if (shares
!= null
) {
1334 // prepare operations to insert or update files to save in the given folder
1335 for (OCShare share
: shares
) {
1336 ContentValues cv
= new ContentValues();
1337 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1338 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1339 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1340 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1341 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1342 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1343 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1344 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1345 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1347 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1348 share
.getSharedWithDisplayName()
1350 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1351 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1352 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1353 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1356 if (shareExists(share.getIdRemoteShared())) {
1357 // updating an existing share resource
1359 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1361 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1362 new String[] { String.valueOf(share.getIdRemoteShared()) })
1367 // adding a new share resource
1369 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1377 // apply operations in batch
1378 if (operations
.size() > 0) {
1379 @SuppressWarnings("unused")
1380 ContentProviderResult
[] results
= null
;
1381 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
1383 if (getContentResolver() != null
) {
1384 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1387 results
= getContentProviderClient().applyBatch(operations
);
1390 } catch (OperationApplicationException e
) {
1391 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1393 } catch (RemoteException e
) {
1394 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1401 private ArrayList
<ContentProviderOperation
> prepareRemoveSharesInFolder(
1402 OCFile folder
, ArrayList
<ContentProviderOperation
> preparedOperations
) {
1403 if (folder
!= null
) {
1404 String where
= ProviderTableMeta
.OCSHARES_PATH
+ "=?" + " AND "
1405 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1406 String
[] whereArgs
= new String
[]{ "", mAccount
.name
};
1408 // TODO Enable when "On Device" is recovered ?
1409 Vector
<OCFile
> files
= getFolderContent(folder
/*, false*/);
1411 for (OCFile file
: files
) {
1412 whereArgs
[0] = file
.getRemotePath();
1413 preparedOperations
.add(
1414 ContentProviderOperation
.newDelete(ProviderTableMeta
.CONTENT_URI_SHARE
).
1415 withSelection(where
, whereArgs
).
1420 return preparedOperations
;
1423 public void triggerMediaScan(String path
) {
1424 Intent intent
= new Intent(Intent
.ACTION_MEDIA_SCANNER_SCAN_FILE
);
1425 intent
.setData(Uri
.fromFile(new File(path
)));
1426 MainApp
.getAppContext().sendBroadcast(intent
);
1429 public void deleteFileInMediaScan(String path
) {
1431 String mimetypeString
= FileStorageUtils
.getMimeTypeFromName(path
);
1432 ContentResolver contentResolver
= getContentResolver();
1434 if (contentResolver
!= null
) {
1435 if (mimetypeString
.startsWith("image/")) {
1437 contentResolver
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1438 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1439 } else if (mimetypeString
.startsWith("audio/")) {
1441 contentResolver
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1442 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1443 } else if (mimetypeString
.startsWith("video/")) {
1445 contentResolver
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1446 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1449 ContentProviderClient contentProviderClient
= getContentProviderClient();
1451 if (mimetypeString
.startsWith("image/")) {
1453 contentProviderClient
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1454 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1455 } else if (mimetypeString
.startsWith("audio/")) {
1457 contentProviderClient
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1458 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1459 } else if (mimetypeString
.startsWith("video/")) {
1461 contentProviderClient
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1462 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1464 } catch (RemoteException e
) {
1465 Log_OC
.e(TAG
, "Exception deleting media file in MediaStore " + e
.getMessage());
1471 public void saveConflict(OCFile file
, boolean inConflict
) {
1472 if (!file
.isDown()) {
1475 ContentValues cv
= new ContentValues();
1476 cv
.put(ProviderTableMeta
.FILE_IN_CONFLICT
, inConflict ?
1 : 0);
1478 if (getContentResolver() != null
) {
1479 updated
= getContentResolver().update(
1480 ProviderTableMeta
.CONTENT_URI_FILE
,
1482 ProviderTableMeta
._ID
+ "=?",
1483 new String
[] { String
.valueOf(file
.getFileId())}
1487 updated
= getContentProviderClient().update(
1488 ProviderTableMeta
.CONTENT_URI_FILE
,
1490 ProviderTableMeta
._ID
+ "=?",
1491 new String
[]{String
.valueOf(file
.getFileId())}
1493 } catch (RemoteException e
) {
1494 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1498 Log_OC
.d(TAG
, "Number of files updated with CONFLICT: " + updated
);
1502 /// set conflict in all ancestor folders
1504 long parentId
= file
.getParentId();
1505 Set
<String
> ancestorIds
= new HashSet
<String
>();
1506 while (parentId
!= FileDataStorageManager
.ROOT_PARENT_ID
) {
1507 ancestorIds
.add(Long
.toString(parentId
));
1508 parentId
= getFileById(parentId
).getParentId();
1511 if (ancestorIds
.size() > 0) {
1512 StringBuffer whereBuffer
= new StringBuffer();
1513 whereBuffer
.append(ProviderTableMeta
._ID
).append(" IN (");
1514 for (int i
= 0; i
< ancestorIds
.size() - 1; i
++) {
1515 whereBuffer
.append("?,");
1517 whereBuffer
.append("?");
1518 whereBuffer
.append(")");
1520 if (getContentResolver() != null
) {
1521 updated
= getContentResolver().update(
1522 ProviderTableMeta
.CONTENT_URI_FILE
,
1524 whereBuffer
.toString(),
1525 ancestorIds
.toArray(new String
[]{})
1529 updated
= getContentProviderClient().update(
1530 ProviderTableMeta
.CONTENT_URI_FILE
,
1532 whereBuffer
.toString(),
1533 ancestorIds
.toArray(new String
[]{})
1535 } catch (RemoteException e
) {
1536 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1539 } // else file is ROOT folder, no parent to set in conflict
1542 /// update conflict in ancestor folders
1543 // (not directly unset; maybe there are more conflicts below them)
1544 String parentPath
= file
.getRemotePath();
1545 if (parentPath
.endsWith(OCFile
.PATH_SEPARATOR
)) {
1546 parentPath
= parentPath
.substring(0, parentPath
.length() - 1);
1548 parentPath
= parentPath
.substring(0, parentPath
.lastIndexOf(OCFile
.PATH_SEPARATOR
) + 1);
1550 Log_OC
.d(TAG
, "checking parents to remove conflict; STARTING with " + parentPath
);
1551 while (parentPath
.length() > 0) {
1554 ProviderTableMeta
.FILE_IN_CONFLICT
+ " = 1 AND " +
1555 ProviderTableMeta
.FILE_CONTENT_TYPE
+ " != 'DIR' AND " +
1556 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ " = ? AND " +
1557 ProviderTableMeta
.FILE_PATH
+ " LIKE ?";
1558 Cursor descendentsInConflict
= getContentResolver().query(
1559 ProviderTableMeta
.CONTENT_URI_FILE
,
1560 new String
[]{ProviderTableMeta
._ID
},
1562 new String
[]{mAccount
.name
, parentPath
+ "%"},
1565 if (descendentsInConflict
== null
|| descendentsInConflict
.getCount() == 0) {
1566 Log_OC
.d(TAG
, "NO MORE conflicts in " + parentPath
);
1567 if (getContentResolver() != null
) {
1568 updated
= getContentResolver().update(
1569 ProviderTableMeta
.CONTENT_URI_FILE
,
1571 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " + ProviderTableMeta
.FILE_PATH
+ "=?",
1572 new String
[]{mAccount
.name
, parentPath
}
1576 updated
= getContentProviderClient().update(
1577 ProviderTableMeta
.CONTENT_URI_FILE
,
1579 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " + ProviderTableMeta
.FILE_PATH
+ "=?"
1580 , new String
[]{mAccount
.name
, parentPath
}
1582 } catch (RemoteException e
) {
1583 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1588 Log_OC
.d(TAG
, "STILL " + descendentsInConflict
.getCount() + " in " + parentPath
);
1591 if (descendentsInConflict
!= null
) {
1592 descendentsInConflict
.close();
1595 parentPath
= parentPath
.substring(0, parentPath
.length() - 1); // trim last /
1596 parentPath
= parentPath
.substring(0, parentPath
.lastIndexOf(OCFile
.PATH_SEPARATOR
) + 1);
1597 Log_OC
.d(TAG
, "checking parents to remove conflict; NEXT " + parentPath
);