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_ETAG_IN_CONFLICT
, file
.getEtagInConflict());
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_ETAG_IN_CONFLICT
, file
.getEtagInConflict());
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
, null
);
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
.setEtagInConflict(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
)));
906 // Methods for Shares
907 public boolean saveShare(OCShare share
) {
908 boolean overriden
= false
;
909 ContentValues cv
= new ContentValues();
910 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
911 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
912 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
913 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
914 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
915 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
916 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
917 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
918 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
920 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
921 share
.getSharedWithDisplayName()
923 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
924 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
925 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
926 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
928 if (shareExists(share
.getIdRemoteShared())) { // for renamed files; no more delete and create
930 if (getContentResolver() != null
) {
931 getContentResolver().update(ProviderTableMeta
.CONTENT_URI_SHARE
, cv
,
932 ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
933 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
936 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI_SHARE
,
937 cv
, ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
938 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
939 } catch (RemoteException e
) {
941 "Fail to insert insert file to database "
946 Uri result_uri
= null
;
947 if (getContentResolver() != null
) {
948 result_uri
= getContentResolver().insert(
949 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
952 result_uri
= getContentProviderClient().insert(
953 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
954 } catch (RemoteException e
) {
956 "Fail to insert insert file to database "
960 if (result_uri
!= null
) {
961 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
971 public OCShare
getFirstShareByPathAndType(String path
, ShareType type
) {
973 if (getContentResolver() != null
) {
974 c
= getContentResolver().query(
975 ProviderTableMeta
.CONTENT_URI_SHARE
,
977 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
978 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
979 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
980 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
984 c
= getContentProviderClient().query(
985 ProviderTableMeta
.CONTENT_URI_SHARE
,
987 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
988 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
989 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
990 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
993 } catch (RemoteException e
) {
994 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
998 OCShare share
= null
;
999 if (c
.moveToFirst()) {
1000 share
= createShareInstance(c
);
1006 private OCShare
createShareInstance(Cursor c
) {
1007 OCShare share
= null
;
1009 share
= new OCShare(c
.getString(c
1010 .getColumnIndex(ProviderTableMeta
.OCSHARES_PATH
)));
1011 share
.setId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
1012 share
.setFileSource(c
.getLong(c
1013 .getColumnIndex(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
)));
1014 share
.setShareType(ShareType
.fromValue(c
.getInt(c
1015 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_TYPE
))));
1016 share
.setPermissions(c
.getInt(c
1017 .getColumnIndex(ProviderTableMeta
.OCSHARES_PERMISSIONS
)));
1018 share
.setSharedDate(c
.getLong(c
1019 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARED_DATE
)));
1020 share
.setExpirationDate(c
.getLong(c
1021 .getColumnIndex(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
)));
1022 share
.setToken(c
.getString(c
1023 .getColumnIndex(ProviderTableMeta
.OCSHARES_TOKEN
)));
1024 share
.setSharedWithDisplayName(c
.getString(c
1025 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
)));
1026 share
.setIsFolder(c
.getInt(
1027 c
.getColumnIndex(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
)) == 1);
1028 share
.setUserId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_USER_ID
)));
1029 share
.setIdRemoteShared(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
)));
1034 private boolean shareExists(String cmp_key
, String value
) {
1036 if (getContentResolver() != null
) {
1037 c
= getContentResolver()
1038 .query(ProviderTableMeta
.CONTENT_URI_SHARE
,
1041 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
1043 new String
[]{value
, mAccount
.name
}, null
);
1046 c
= getContentProviderClient().query(
1047 ProviderTableMeta
.CONTENT_URI_SHARE
,
1050 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
1051 new String
[]{value
, mAccount
.name
}, null
);
1052 } catch (RemoteException e
) {
1054 "Couldn't determine file existance, assuming non existance: "
1059 boolean retval
= c
.moveToFirst();
1064 private boolean shareExists(long remoteId
) {
1065 return shareExists(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, String
.valueOf(remoteId
));
1068 private void cleanSharedFiles() {
1069 ContentValues cv
= new ContentValues();
1070 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1071 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1072 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?";
1073 String
[] whereArgs
= new String
[]{mAccount
.name
};
1075 if (getContentResolver() != null
) {
1076 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1080 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1081 } catch (RemoteException e
) {
1082 Log_OC
.e(TAG
, "Exception in cleanSharedFiles" + e
.getMessage());
1087 private void cleanSharedFilesInFolder(OCFile folder
) {
1088 ContentValues cv
= new ContentValues();
1089 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1090 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1091 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1092 ProviderTableMeta
.FILE_PARENT
+ "=?";
1093 String
[] whereArgs
= new String
[] { mAccount
.name
, String
.valueOf(folder
.getFileId()) };
1095 if (getContentResolver() != null
) {
1096 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1100 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1101 } catch (RemoteException e
) {
1102 Log_OC
.e(TAG
, "Exception in cleanSharedFilesInFolder " + e
.getMessage());
1107 private void cleanShares() {
1108 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1109 String
[] whereArgs
= new String
[]{mAccount
.name
};
1111 if (getContentResolver() != null
) {
1112 getContentResolver().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1116 getContentProviderClient().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1117 } catch (RemoteException e
) {
1118 Log_OC
.e(TAG
, "Exception in cleanShares" + e
.getMessage());
1123 public void saveShares(Collection
<OCShare
> shares
) {
1125 if (shares
!= null
) {
1126 ArrayList
<ContentProviderOperation
> operations
=
1127 new ArrayList
<ContentProviderOperation
>(shares
.size());
1129 // prepare operations to insert or update files to save in the given folder
1130 for (OCShare share
: shares
) {
1131 ContentValues cv
= new ContentValues();
1132 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1133 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1134 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1135 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1136 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1137 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1138 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1139 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1140 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1142 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1143 share
.getSharedWithDisplayName()
1145 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1146 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1147 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1148 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1150 if (shareExists(share
.getIdRemoteShared())) {
1151 // updating an existing file
1153 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI_SHARE
).
1155 withSelection(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
1156 new String
[]{String
.valueOf(share
.getIdRemoteShared())})
1159 // adding a new file
1161 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1168 // apply operations in batch
1169 if (operations
.size() > 0) {
1170 @SuppressWarnings("unused")
1171 ContentProviderResult
[] results
= null
;
1172 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1173 " operations to FileContentProvider");
1175 if (getContentResolver() != null
) {
1176 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1178 results
= getContentProviderClient().applyBatch(operations
);
1181 } catch (OperationApplicationException e
) {
1182 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1184 } catch (RemoteException e
) {
1185 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1192 public void updateSharedFiles(Collection
<OCFile
> sharedFiles
) {
1195 if (sharedFiles
!= null
) {
1196 ArrayList
<ContentProviderOperation
> operations
=
1197 new ArrayList
<ContentProviderOperation
>(sharedFiles
.size());
1199 // prepare operations to insert or update files to save in the given folder
1200 for (OCFile file
: sharedFiles
) {
1201 ContentValues cv
= new ContentValues();
1202 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
1204 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
1205 file
.getModificationTimestampAtLastSyncForData()
1207 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
1208 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
1209 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
1210 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
1211 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
1212 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
1213 if (!file
.isFolder()) {
1214 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
1216 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
1217 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
1219 ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
,
1220 file
.getLastSyncDateForData()
1222 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
1223 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
1224 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
1225 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
1226 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
1227 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
1229 ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
,
1230 file
.needsUpdateThumbnail() ?
1 : 0
1233 ProviderTableMeta
.FILE_IS_DOWNLOADING
,
1234 file
.isDownloading() ?
1 : 0
1236 cv
.put(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
, file
.getEtagInConflict());
1238 boolean existsByPath
= fileExists(file
.getRemotePath());
1239 if (existsByPath
|| fileExists(file
.getFileId())) {
1240 // updating an existing file
1242 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
1244 withSelection(ProviderTableMeta
._ID
+ "=?",
1245 new String
[]{String
.valueOf(file
.getFileId())})
1249 // adding a new file
1251 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
1258 // apply operations in batch
1259 if (operations
.size() > 0) {
1260 @SuppressWarnings("unused")
1261 ContentProviderResult
[] results
= null
;
1262 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1263 " operations to FileContentProvider");
1265 if (getContentResolver() != null
) {
1266 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1268 results
= getContentProviderClient().applyBatch(operations
);
1271 } catch (OperationApplicationException e
) {
1272 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1274 } catch (RemoteException e
) {
1275 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1282 public void removeShare(OCShare share
) {
1283 Uri share_uri
= ProviderTableMeta
.CONTENT_URI_SHARE
;
1284 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?" + " AND " +
1285 ProviderTableMeta
.FILE_PATH
+ "=?";
1286 String
[] whereArgs
= new String
[]{mAccount
.name
, share
.getPath()};
1287 if (getContentProviderClient() != null
) {
1289 getContentProviderClient().delete(share_uri
, where
, whereArgs
);
1290 } catch (RemoteException e
) {
1291 e
.printStackTrace();
1294 getContentResolver().delete(share_uri
, where
, whereArgs
);
1298 public void saveSharesDB(ArrayList
<OCShare
> shares
) {
1301 ArrayList
<OCFile
> sharedFiles
= new ArrayList
<OCFile
>();
1303 for (OCShare share
: shares
) {
1305 String path
= share
.getPath();
1306 if (share
.isFolder()) {
1307 path
= path
+ FileUtils
.PATH_SEPARATOR
;
1310 // Update OCFile with data from share: ShareByLink and publicLink
1311 OCFile file
= getFileByPath(path
);
1313 if (share
.getShareType().equals(ShareType
.PUBLIC_LINK
)) {
1314 file
.setShareByLink(true
);
1315 sharedFiles
.add(file
);
1320 updateSharedFiles(sharedFiles
);
1324 public void saveSharesInFolder(ArrayList
<OCShare
> shares
, OCFile folder
) {
1325 cleanSharedFilesInFolder(folder
);
1326 ArrayList
<ContentProviderOperation
> operations
= new ArrayList
<ContentProviderOperation
>();
1327 operations
= prepareRemoveSharesInFolder(folder
, operations
);
1329 if (shares
!= null
) {
1330 // prepare operations to insert or update files to save in the given folder
1331 for (OCShare share
: shares
) {
1332 ContentValues cv
= new ContentValues();
1333 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1334 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1335 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1336 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1337 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1338 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1339 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1340 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1341 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1343 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1344 share
.getSharedWithDisplayName()
1346 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1347 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1348 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1349 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1352 if (shareExists(share.getIdRemoteShared())) {
1353 // updating an existing share resource
1355 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1357 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1358 new String[] { String.valueOf(share.getIdRemoteShared()) })
1363 // adding a new share resource
1365 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1373 // apply operations in batch
1374 if (operations
.size() > 0) {
1375 @SuppressWarnings("unused")
1376 ContentProviderResult
[] results
= null
;
1377 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
1379 if (getContentResolver() != null
) {
1380 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1383 results
= getContentProviderClient().applyBatch(operations
);
1386 } catch (OperationApplicationException e
) {
1387 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1389 } catch (RemoteException e
) {
1390 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1397 private ArrayList
<ContentProviderOperation
> prepareRemoveSharesInFolder(
1398 OCFile folder
, ArrayList
<ContentProviderOperation
> preparedOperations
) {
1399 if (folder
!= null
) {
1400 String where
= ProviderTableMeta
.OCSHARES_PATH
+ "=?" + " AND "
1401 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1402 String
[] whereArgs
= new String
[]{ "", mAccount
.name
};
1404 // TODO Enable when "On Device" is recovered ?
1405 Vector
<OCFile
> files
= getFolderContent(folder
/*, false*/);
1407 for (OCFile file
: files
) {
1408 whereArgs
[0] = file
.getRemotePath();
1409 preparedOperations
.add(
1410 ContentProviderOperation
.newDelete(ProviderTableMeta
.CONTENT_URI_SHARE
).
1411 withSelection(where
, whereArgs
).
1416 return preparedOperations
;
1419 public void triggerMediaScan(String path
) {
1420 Intent intent
= new Intent(Intent
.ACTION_MEDIA_SCANNER_SCAN_FILE
);
1421 intent
.setData(Uri
.fromFile(new File(path
)));
1422 MainApp
.getAppContext().sendBroadcast(intent
);
1425 public void deleteFileInMediaScan(String path
) {
1427 String mimetypeString
= FileStorageUtils
.getMimeTypeFromName(path
);
1428 ContentResolver contentResolver
= getContentResolver();
1430 if (contentResolver
!= null
) {
1431 if (mimetypeString
.startsWith("image/")) {
1433 contentResolver
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1434 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1435 } else if (mimetypeString
.startsWith("audio/")) {
1437 contentResolver
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1438 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1439 } else if (mimetypeString
.startsWith("video/")) {
1441 contentResolver
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1442 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1445 ContentProviderClient contentProviderClient
= getContentProviderClient();
1447 if (mimetypeString
.startsWith("image/")) {
1449 contentProviderClient
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1450 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1451 } else if (mimetypeString
.startsWith("audio/")) {
1453 contentProviderClient
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1454 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1455 } else if (mimetypeString
.startsWith("video/")) {
1457 contentProviderClient
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1458 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1460 } catch (RemoteException e
) {
1461 Log_OC
.e(TAG
, "Exception deleting media file in MediaStore " + e
.getMessage());
1467 public void saveConflict(OCFile file
, String etagInConflict
) {
1468 if (!file
.isDown()) {
1469 etagInConflict
= null
;
1471 ContentValues cv
= new ContentValues();
1472 cv
.put(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
, etagInConflict
);
1474 if (getContentResolver() != null
) {
1475 updated
= getContentResolver().update(
1476 ProviderTableMeta
.CONTENT_URI_FILE
,
1478 ProviderTableMeta
._ID
+ "=?",
1479 new String
[] { String
.valueOf(file
.getFileId())}
1483 updated
= getContentProviderClient().update(
1484 ProviderTableMeta
.CONTENT_URI_FILE
,
1486 ProviderTableMeta
._ID
+ "=?",
1487 new String
[]{String
.valueOf(file
.getFileId())}
1489 } catch (RemoteException e
) {
1490 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1494 Log_OC
.d(TAG
, "Number of files updated with CONFLICT: " + updated
);
1497 if (etagInConflict
!= null
) {
1498 /// set conflict in all ancestor folders
1500 long parentId
= file
.getParentId();
1501 Set
<String
> ancestorIds
= new HashSet
<String
>();
1502 while (parentId
!= FileDataStorageManager
.ROOT_PARENT_ID
) {
1503 ancestorIds
.add(Long
.toString(parentId
));
1504 parentId
= getFileById(parentId
).getParentId();
1507 if (ancestorIds
.size() > 0) {
1508 StringBuffer whereBuffer
= new StringBuffer();
1509 whereBuffer
.append(ProviderTableMeta
._ID
).append(" IN (");
1510 for (int i
= 0; i
< ancestorIds
.size() - 1; i
++) {
1511 whereBuffer
.append("?,");
1513 whereBuffer
.append("?");
1514 whereBuffer
.append(")");
1516 if (getContentResolver() != null
) {
1517 updated
= getContentResolver().update(
1518 ProviderTableMeta
.CONTENT_URI_FILE
,
1520 whereBuffer
.toString(),
1521 ancestorIds
.toArray(new String
[]{})
1525 updated
= getContentProviderClient().update(
1526 ProviderTableMeta
.CONTENT_URI_FILE
,
1528 whereBuffer
.toString(),
1529 ancestorIds
.toArray(new String
[]{})
1531 } catch (RemoteException e
) {
1532 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1535 } // else file is ROOT folder, no parent to set in conflict
1538 /// update conflict in ancestor folders
1539 // (not directly unset; maybe there are more conflicts below them)
1540 String parentPath
= file
.getRemotePath();
1541 if (parentPath
.endsWith(OCFile
.PATH_SEPARATOR
)) {
1542 parentPath
= parentPath
.substring(0, parentPath
.length() - 1);
1544 parentPath
= parentPath
.substring(0, parentPath
.lastIndexOf(OCFile
.PATH_SEPARATOR
) + 1);
1546 Log_OC
.d(TAG
, "checking parents to remove conflict; STARTING with " + parentPath
);
1547 while (parentPath
.length() > 0) {
1550 ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
+ " IS NOT NULL AND " +
1551 ProviderTableMeta
.FILE_CONTENT_TYPE
+ " != 'DIR' AND " +
1552 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ " = ? AND " +
1553 ProviderTableMeta
.FILE_PATH
+ " LIKE ?";
1554 Cursor descendentsInConflict
= getContentResolver().query(
1555 ProviderTableMeta
.CONTENT_URI_FILE
,
1556 new String
[]{ProviderTableMeta
._ID
},
1558 new String
[]{mAccount
.name
, parentPath
+ "%"},
1561 if (descendentsInConflict
== null
|| descendentsInConflict
.getCount() == 0) {
1562 Log_OC
.d(TAG
, "NO MORE conflicts in " + parentPath
);
1563 if (getContentResolver() != null
) {
1564 updated
= getContentResolver().update(
1565 ProviderTableMeta
.CONTENT_URI_FILE
,
1567 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1568 ProviderTableMeta
.FILE_PATH
+ "=?",
1569 new String
[]{mAccount
.name
, parentPath
}
1573 updated
= getContentProviderClient().update(
1574 ProviderTableMeta
.CONTENT_URI_FILE
,
1576 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1577 ProviderTableMeta
.FILE_PATH
+ "=?"
1578 , new String
[]{mAccount
.name
, parentPath
}
1580 } catch (RemoteException e
) {
1581 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1586 Log_OC
.d(TAG
, "STILL " + descendentsInConflict
.getCount() + " in " + parentPath
);
1589 if (descendentsInConflict
!= null
) {
1590 descendentsInConflict
.close();
1593 parentPath
= parentPath
.substring(0, parentPath
.length() - 1); // trim last /
1594 parentPath
= parentPath
.substring(0, parentPath
.lastIndexOf(OCFile
.PATH_SEPARATOR
) + 1);
1595 Log_OC
.d(TAG
, "checking parents to remove conflict; NEXT " + parentPath
);