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 return getFolderContent(f
.getFileId(), onlyOnDevice
);
150 return new Vector
<OCFile
>();
155 public Vector
<OCFile
> getFolderImages(OCFile folder
, boolean onlyOnDevice
) {
156 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
157 if (folder
!= null
) {
158 // TODO better implementation, filtering in the access to database instead of here
159 Vector
<OCFile
> tmp
= getFolderContent(folder
, onlyOnDevice
);
160 OCFile current
= null
;
161 for (int i
=0; i
<tmp
.size(); i
++) {
162 current
= tmp
.get(i
);
163 if (current
.isImage()) {
171 public boolean saveFile(OCFile file
) {
172 boolean overriden
= false
;
173 ContentValues cv
= new ContentValues();
174 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
176 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
177 file
.getModificationTimestampAtLastSyncForData()
179 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
180 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
181 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
182 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
183 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
184 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
185 if (!file
.isFolder())
186 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
187 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
188 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
189 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, file
.getLastSyncDateForData());
190 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
191 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
192 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
193 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
194 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
195 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
196 cv
.put(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
, file
.needsUpdateThumbnail());
197 cv
.put(ProviderTableMeta
.FILE_IS_DOWNLOADING
, file
.isDownloading());
198 cv
.put(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
, file
.getEtagInConflict());
200 boolean sameRemotePath
= fileExists(file
.getRemotePath());
201 if (sameRemotePath
|| fileExists(file
.getFileId())) { // for renamed files; no more delete and create
204 if (sameRemotePath
) {
205 oldFile
= getFileByPath(file
.getRemotePath());
206 file
.setFileId(oldFile
.getFileId());
208 oldFile
= getFileById(file
.getFileId());
212 if (getContentResolver() != null
) {
213 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
,
214 ProviderTableMeta
._ID
+ "=?",
215 new String
[]{String
.valueOf(file
.getFileId())});
218 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
,
219 cv
, ProviderTableMeta
._ID
+ "=?",
220 new String
[]{String
.valueOf(file
.getFileId())});
221 } catch (RemoteException e
) {
223 "Fail to insert insert file to database "
228 Uri result_uri
= null
;
229 if (getContentResolver() != null
) {
230 result_uri
= getContentResolver().insert(
231 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
234 result_uri
= getContentProviderClient().insert(
235 ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
236 } catch (RemoteException e
) {
238 "Fail to insert insert file to database "
242 if (result_uri
!= null
) {
243 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
245 file
.setFileId(new_id
);
254 * Inserts or updates the list of files contained in a given folder.
256 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
257 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
260 * @param updatedFiles
261 * @param filesToRemove
263 public void saveFolder(
264 OCFile folder
, Collection
<OCFile
> updatedFiles
, Collection
<OCFile
> filesToRemove
267 Log_OC
.d(TAG
, "Saving folder " + folder
.getRemotePath() + " with " + updatedFiles
.size()
268 + " children and " + filesToRemove
.size() + " files to remove");
270 ArrayList
<ContentProviderOperation
> operations
=
271 new ArrayList
<ContentProviderOperation
>(updatedFiles
.size());
273 // prepare operations to insert or update files to save in the given folder
274 for (OCFile file
: updatedFiles
) {
275 ContentValues cv
= new ContentValues();
276 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
278 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
279 file
.getModificationTimestampAtLastSyncForData()
281 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
282 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
283 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
284 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
285 //cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
286 cv
.put(ProviderTableMeta
.FILE_PARENT
, folder
.getFileId());
287 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
288 if (!file
.isFolder()) {
289 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
291 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
292 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
293 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, file
.getLastSyncDateForData());
294 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
295 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
296 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
297 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
298 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
299 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
300 cv
.put(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
, file
.needsUpdateThumbnail());
301 cv
.put(ProviderTableMeta
.FILE_IS_DOWNLOADING
, file
.isDownloading());
302 cv
.put(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
, file
.getEtagInConflict());
304 boolean existsByPath
= fileExists(file
.getRemotePath());
305 if (existsByPath
|| fileExists(file
.getFileId())) {
306 // updating an existing file
307 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
309 withSelection(ProviderTableMeta
._ID
+ "=?",
310 new String
[]{String
.valueOf(file
.getFileId())})
315 operations
.add(ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
316 withValues(cv
).build());
320 // prepare operations to remove files in the given folder
321 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " +
322 ProviderTableMeta
.FILE_PATH
+ "=?";
323 String
[] whereArgs
= null
;
324 for (OCFile file
: filesToRemove
) {
325 if (file
.getParentId() == folder
.getFileId()) {
326 whereArgs
= new String
[]{mAccount
.name
, file
.getRemotePath()};
327 if (file
.isFolder()) {
328 operations
.add(ContentProviderOperation
.newDelete(
329 ContentUris
.withAppendedId(
330 ProviderTableMeta
.CONTENT_URI_DIR
, file
.getFileId()
332 ).withSelection(where
, whereArgs
).build());
335 new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
336 if (localFolder
.exists()) {
337 removeLocalFolder(localFolder
);
340 operations
.add(ContentProviderOperation
.newDelete(
341 ContentUris
.withAppendedId(
342 ProviderTableMeta
.CONTENT_URI_FILE
, file
.getFileId()
344 ).withSelection(where
, whereArgs
).build());
347 String path
= file
.getStoragePath();
348 new File(path
).delete();
349 triggerMediaScan(path
); // notify MediaScanner about removed file
355 // update metadata of folder
356 ContentValues cv
= new ContentValues();
357 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, folder
.getModificationTimestamp());
359 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
360 folder
.getModificationTimestampAtLastSyncForData()
362 cv
.put(ProviderTableMeta
.FILE_CREATION
, folder
.getCreationTimestamp());
363 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, 0);
364 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, folder
.getMimetype());
365 cv
.put(ProviderTableMeta
.FILE_NAME
, folder
.getFileName());
366 cv
.put(ProviderTableMeta
.FILE_PARENT
, folder
.getParentId());
367 cv
.put(ProviderTableMeta
.FILE_PATH
, folder
.getRemotePath());
368 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
369 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, folder
.getLastSyncDateForProperties());
370 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
, folder
.getLastSyncDateForData());
371 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, folder
.isFavorite() ?
1 : 0);
372 cv
.put(ProviderTableMeta
.FILE_ETAG
, folder
.getEtag());
373 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, folder
.isShareByLink() ?
1 : 0);
374 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, folder
.getPublicLink());
375 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, folder
.getPermissions());
376 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, folder
.getRemoteId());
378 operations
.add(ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
380 withSelection(ProviderTableMeta
._ID
+ "=?",
381 new String
[]{String
.valueOf(folder
.getFileId())})
384 // apply operations in batch
385 ContentProviderResult
[] results
= null
;
386 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
388 if (getContentResolver() != null
) {
389 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
392 results
= getContentProviderClient().applyBatch(operations
);
395 } catch (OperationApplicationException e
) {
396 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
398 } catch (RemoteException e
) {
399 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
402 // update new id in file objects for insertions
403 if (results
!= null
) {
405 Iterator
<OCFile
> filesIt
= updatedFiles
.iterator();
407 for (int i
= 0; i
< results
.length
; i
++) {
408 if (filesIt
.hasNext()) {
409 file
= filesIt
.next();
413 if (results
[i
].uri
!= null
) {
414 newId
= Long
.parseLong(results
[i
].uri
.getPathSegments().get(1));
415 //updatedFiles.get(i).setFileId(newId);
417 file
.setFileId(newId
);
426 public boolean removeFile(OCFile file
, boolean removeDBData
, boolean removeLocalCopy
) {
427 boolean success
= true
;
429 if (file
.isFolder()) {
430 success
= removeFolder(file
, removeDBData
, removeLocalCopy
);
434 //Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
435 Uri file_uri
= ContentUris
.withAppendedId(ProviderTableMeta
.CONTENT_URI_FILE
, file
.getFileId());
436 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " + ProviderTableMeta
.FILE_PATH
+ "=?";
437 String
[] whereArgs
= new String
[]{mAccount
.name
, file
.getRemotePath()};
439 if (getContentProviderClient() != null
) {
441 deleted
= getContentProviderClient().delete(file_uri
, where
, whereArgs
);
442 } catch (RemoteException e
) {
446 deleted
= getContentResolver().delete(file_uri
, where
, whereArgs
);
448 success
&= (deleted
> 0);
450 String localPath
= file
.getStoragePath();
451 if (removeLocalCopy
&& file
.isDown() && localPath
!= null
&& success
) {
452 success
= new File(localPath
).delete();
454 deleteFileInMediaScan(localPath
);
456 if (!removeDBData
&& success
) {
457 // maybe unnecessary, but should be checked TODO remove if unnecessary
458 file
.setStoragePath(null
);
460 saveConflict(file
, null
);
469 public boolean removeFolder(OCFile folder
, boolean removeDBData
, boolean removeLocalContent
) {
470 boolean success
= true
;
471 if (folder
!= null
&& folder
.isFolder()) {
472 if (removeDBData
&& folder
.getFileId() != -1) {
473 success
= removeFolderInDb(folder
);
475 if (removeLocalContent
&& success
) {
476 success
= removeLocalFolder(folder
);
482 private boolean removeFolderInDb(OCFile folder
) {
483 Uri folder_uri
= Uri
.withAppendedPath(ProviderTableMeta
.CONTENT_URI_DIR
, "" +
484 folder
.getFileId()); // URI for recursive deletion
485 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?" + " AND " +
486 ProviderTableMeta
.FILE_PATH
+ "=?";
487 String
[] whereArgs
= new String
[]{mAccount
.name
, folder
.getRemotePath()};
489 if (getContentProviderClient() != null
) {
491 deleted
= getContentProviderClient().delete(folder_uri
, where
, whereArgs
);
492 } catch (RemoteException e
) {
496 deleted
= getContentResolver().delete(folder_uri
, where
, whereArgs
);
501 private boolean removeLocalFolder(OCFile folder
) {
502 boolean success
= true
;
503 String localFolderPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, folder
);
504 File localFolder
= new File(localFolderPath
);
505 if (localFolder
.exists()) {
506 // stage 1: remove the local files already registered in the files database
507 Vector
<OCFile
> files
= getFolderContent(folder
.getFileId(), false
);
509 for (OCFile file
: files
) {
510 if (file
.isFolder()) {
511 success
&= removeLocalFolder(file
);
514 File localFile
= new File(file
.getStoragePath());
515 success
&= localFile
.delete();
517 // notify MediaScanner about removed file
518 deleteFileInMediaScan(file
.getStoragePath());
519 file
.setStoragePath(null
);
527 // stage 2: remove the folder itself and any local file inside out of sync;
528 // for instance, after clearing the app cache or reinstalling
529 success
&= removeLocalFolder(localFolder
);
534 private boolean removeLocalFolder(File localFolder
) {
535 boolean success
= true
;
536 File
[] localFiles
= localFolder
.listFiles();
537 if (localFiles
!= null
) {
538 for (File localFile
: localFiles
) {
539 if (localFile
.isDirectory()) {
540 success
&= removeLocalFolder(localFile
);
542 String path
= localFile
.getAbsolutePath();
543 success
&= localFile
.delete();
547 success
&= localFolder
.delete();
553 * Updates database and file system for a file or folder that was moved to a different location.
555 * TODO explore better (faster) implementations
556 * TODO throw exceptions up !
558 public void moveLocalFile(OCFile file
, String targetPath
, String targetParentPath
) {
560 if (file
!= null
&& file
.fileExists() && !OCFile
.ROOT_PATH
.equals(file
.getFileName())) {
562 OCFile targetParent
= getFileByPath(targetParentPath
);
563 if (targetParent
== null
) {
564 throw new IllegalStateException("Parent folder of the target path does not exist!!");
567 /// 1. get all the descendants of the moved element in a single QUERY
569 if (getContentProviderClient() != null
) {
571 c
= getContentProviderClient().query(
572 ProviderTableMeta
.CONTENT_URI
,
574 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
575 ProviderTableMeta
.FILE_PATH
+ " LIKE ? ",
578 file
.getRemotePath() + "%"
580 ProviderTableMeta
.FILE_PATH
+ " ASC "
582 } catch (RemoteException e
) {
583 Log_OC
.e(TAG
, e
.getMessage());
587 c
= getContentResolver().query(
588 ProviderTableMeta
.CONTENT_URI
,
590 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
591 ProviderTableMeta
.FILE_PATH
+ " LIKE ? ",
594 file
.getRemotePath() + "%"
596 ProviderTableMeta
.FILE_PATH
+ " ASC "
600 /// 2. prepare a batch of update operations to change all the descendants
601 ArrayList
<ContentProviderOperation
> operations
=
602 new ArrayList
<ContentProviderOperation
>(c
.getCount());
603 String defaultSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
604 List
<String
> originalPathsToTriggerMediaScan
= new ArrayList
<String
>();
605 List
<String
> newPathsToTriggerMediaScan
= new ArrayList
<String
>();
606 if (c
.moveToFirst()) {
607 int lengthOfOldPath
= file
.getRemotePath().length();
608 int lengthOfOldStoragePath
= defaultSavePath
.length() + lengthOfOldPath
;
610 ContentValues cv
= new ContentValues(); // keep construction in the loop
611 OCFile child
= createFileInstance(c
);
613 ProviderTableMeta
.FILE_PATH
,
614 targetPath
+ child
.getRemotePath().substring(lengthOfOldPath
)
616 if (child
.getStoragePath() != null
&&
617 child
.getStoragePath().startsWith(defaultSavePath
)) {
618 // update link to downloaded content - but local move is not done here!
619 String targetLocalPath
= defaultSavePath
+ targetPath
+
620 child
.getStoragePath().substring(lengthOfOldStoragePath
);
622 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, targetLocalPath
);
624 originalPathsToTriggerMediaScan
.add(child
.getStoragePath());
625 newPathsToTriggerMediaScan
.add(targetLocalPath
);
628 if (child
.getRemotePath().equals(file
.getRemotePath())) {
630 ProviderTableMeta
.FILE_PARENT
,
631 targetParent
.getFileId()
635 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
638 ProviderTableMeta
._ID
+ "=?",
639 new String
[]{String
.valueOf(child
.getFileId())}
643 } while (c
.moveToNext());
647 /// 3. apply updates in batch
649 if (getContentResolver() != null
) {
650 getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
653 getContentProviderClient().applyBatch(operations
);
656 } catch (Exception e
) {
657 Log_OC
.e(TAG
, "Fail to update " + file
.getFileId() + " and descendants in database", e
);
660 /// 4. move in local file system
661 String originalLocalPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
662 String targetLocalPath
= defaultSavePath
+ targetPath
;
663 File localFile
= new File(originalLocalPath
);
664 boolean renamed
= false
;
665 if (localFile
.exists()) {
666 File targetFile
= new File(targetLocalPath
);
667 File targetFolder
= targetFile
.getParentFile();
668 if (!targetFolder
.exists()) {
669 targetFolder
.mkdirs();
671 renamed
= localFile
.renameTo(targetFile
);
675 Iterator
<String
> it
= originalPathsToTriggerMediaScan
.iterator();
676 while (it
.hasNext()) {
677 // Notify MediaScanner about removed file
678 deleteFileInMediaScan(it
.next());
680 it
= newPathsToTriggerMediaScan
.iterator();
681 while (it
.hasNext()) {
682 // Notify MediaScanner about new file/folder
683 triggerMediaScan(it
.next());
690 public void copyLocalFile(OCFile file
, String targetPath
) {
692 if (file
!= null
&& file
.fileExists() && !OCFile
.ROOT_PATH
.equals(file
.getFileName())) {
693 String localPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
694 File localFile
= new File(localPath
);
695 boolean copied
= false
;
696 String defaultSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
697 if (localFile
.exists()) {
698 File targetFile
= new File(defaultSavePath
+ targetPath
);
699 File targetFolder
= targetFile
.getParentFile();
700 if (!targetFolder
.exists()) {
701 targetFolder
.mkdirs();
703 copied
= copyFile(localFile
, targetFile
);
705 Log_OC
.d(TAG
, "Local file COPIED : " + copied
);
709 private boolean copyFile(File src
, File target
) {
712 InputStream
in = null
;
713 OutputStream out
= null
;
716 in = new FileInputStream(src
);
717 out
= new FileOutputStream(target
);
718 byte[] buf
= new byte[1024];
720 while ((len
= in.read(buf
)) > 0) {
721 out
.write(buf
, 0, len
);
723 } catch (IOException ex
) {
726 if (in != null
) try {
728 } catch (IOException e
) {
729 e
.printStackTrace(System
.err
);
731 if (out
!= null
) try {
733 } catch (IOException e
) {
734 e
.printStackTrace(System
.err
);
742 private Vector
<OCFile
> getFolderContent(long parentId
, boolean onlyOnDevice
) {
744 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
746 Uri req_uri
= Uri
.withAppendedPath(
747 ProviderTableMeta
.CONTENT_URI_DIR
,
748 String
.valueOf(parentId
));
751 if (getContentProviderClient() != null
) {
753 c
= getContentProviderClient().query(req_uri
, null
,
754 ProviderTableMeta
.FILE_PARENT
+ "=?",
755 new String
[]{String
.valueOf(parentId
)}, null
);
756 } catch (RemoteException e
) {
757 Log_OC
.e(TAG
, e
.getMessage());
761 c
= getContentResolver().query(req_uri
, null
,
762 ProviderTableMeta
.FILE_PARENT
+ "=?",
763 new String
[]{String
.valueOf(parentId
)}, null
);
766 if (c
.moveToFirst()) {
768 OCFile child
= createFileInstance(c
);
769 if (child
.isFolder() || !onlyOnDevice
|| onlyOnDevice
&& child
.isDown()){
772 } while (c
.moveToNext());
777 Collections
.sort(ret
);
783 private OCFile
createRootDir() {
784 OCFile file
= new OCFile(OCFile
.ROOT_PATH
);
785 file
.setMimetype("DIR");
786 file
.setParentId(FileDataStorageManager
.ROOT_PARENT_ID
);
791 private boolean fileExists(String cmp_key
, String value
) {
793 if (getContentResolver() != null
) {
794 c
= getContentResolver()
795 .query(ProviderTableMeta
.CONTENT_URI
,
798 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
800 new String
[]{value
, mAccount
.name
}, null
);
803 c
= getContentProviderClient().query(
804 ProviderTableMeta
.CONTENT_URI
,
807 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
808 new String
[]{value
, mAccount
.name
}, null
);
809 } catch (RemoteException e
) {
811 "Couldn't determine file existance, assuming non existance: "
816 boolean retval
= c
.moveToFirst();
821 private Cursor
getCursorForValue(String key
, String value
) {
823 if (getContentResolver() != null
) {
824 c
= getContentResolver()
825 .query(ProviderTableMeta
.CONTENT_URI
,
828 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
830 new String
[]{value
, mAccount
.name
}, null
);
833 c
= getContentProviderClient().query(
834 ProviderTableMeta
.CONTENT_URI
,
836 key
+ "=? AND " + ProviderTableMeta
.FILE_ACCOUNT_OWNER
837 + "=?", new String
[]{value
, mAccount
.name
},
839 } catch (RemoteException e
) {
840 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
848 private OCFile
createFileInstance(Cursor c
) {
851 file
= new OCFile(c
.getString(c
852 .getColumnIndex(ProviderTableMeta
.FILE_PATH
)));
853 file
.setFileId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
854 file
.setParentId(c
.getLong(c
855 .getColumnIndex(ProviderTableMeta
.FILE_PARENT
)));
856 file
.setMimetype(c
.getString(c
857 .getColumnIndex(ProviderTableMeta
.FILE_CONTENT_TYPE
)));
858 if (!file
.isFolder()) {
859 file
.setStoragePath(c
.getString(c
860 .getColumnIndex(ProviderTableMeta
.FILE_STORAGE_PATH
)));
861 if (file
.getStoragePath() == null
) {
862 // try to find existing file and bind it with current account;
863 // with the current update of SynchronizeFolderOperation, this won't be
864 // necessary anymore after a full synchronization of the account
865 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
867 file
.setStoragePath(f
.getAbsolutePath());
868 file
.setLastSyncDateForData(f
.lastModified());
872 file
.setFileLength(c
.getLong(c
873 .getColumnIndex(ProviderTableMeta
.FILE_CONTENT_LENGTH
)));
874 file
.setCreationTimestamp(c
.getLong(c
875 .getColumnIndex(ProviderTableMeta
.FILE_CREATION
)));
876 file
.setModificationTimestamp(c
.getLong(c
877 .getColumnIndex(ProviderTableMeta
.FILE_MODIFIED
)));
878 file
.setModificationTimestampAtLastSyncForData(c
.getLong(c
879 .getColumnIndex(ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
)));
880 file
.setLastSyncDateForProperties(c
.getLong(c
881 .getColumnIndex(ProviderTableMeta
.FILE_LAST_SYNC_DATE
)));
882 file
.setLastSyncDateForData(c
.getLong(c
.
883 getColumnIndex(ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
)));
884 file
.setFavorite(c
.getInt(
885 c
.getColumnIndex(ProviderTableMeta
.FILE_KEEP_IN_SYNC
)) == 1 ? true
: false
);
886 file
.setEtag(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_ETAG
)));
887 file
.setShareByLink(c
.getInt(
888 c
.getColumnIndex(ProviderTableMeta
.FILE_SHARE_BY_LINK
)) == 1 ? true
: false
);
889 file
.setPublicLink(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_PUBLIC_LINK
)));
890 file
.setPermissions(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_PERMISSIONS
)));
891 file
.setRemoteId(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_REMOTE_ID
)));
892 file
.setNeedsUpdateThumbnail(c
.getInt(
893 c
.getColumnIndex(ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
)) == 1 ? true
: false
);
894 file
.setDownloading(c
.getInt(
895 c
.getColumnIndex(ProviderTableMeta
.FILE_IS_DOWNLOADING
)) == 1 ? true
: false
);
896 file
.setEtagInConflict(c
.getString(c
.getColumnIndex(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
)));
902 // Methods for Shares
903 public boolean saveShare(OCShare share
) {
904 boolean overriden
= false
;
905 ContentValues cv
= new ContentValues();
906 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
907 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
908 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
909 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
910 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
911 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
912 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
913 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
914 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
916 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
917 share
.getSharedWithDisplayName()
919 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
920 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
921 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
922 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
924 if (shareExists(share
.getIdRemoteShared())) { // for renamed files; no more delete and create
926 if (getContentResolver() != null
) {
927 getContentResolver().update(ProviderTableMeta
.CONTENT_URI_SHARE
, cv
,
928 ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
929 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
932 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI_SHARE
,
933 cv
, ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
934 new String
[]{String
.valueOf(share
.getIdRemoteShared())});
935 } catch (RemoteException e
) {
937 "Fail to insert insert file to database "
942 Uri result_uri
= null
;
943 if (getContentResolver() != null
) {
944 result_uri
= getContentResolver().insert(
945 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
948 result_uri
= getContentProviderClient().insert(
949 ProviderTableMeta
.CONTENT_URI_SHARE
, cv
);
950 } catch (RemoteException e
) {
952 "Fail to insert insert file to database "
956 if (result_uri
!= null
) {
957 long new_id
= Long
.parseLong(result_uri
.getPathSegments()
967 public OCShare
getFirstShareByPathAndType(String path
, ShareType type
) {
969 if (getContentResolver() != null
) {
970 c
= getContentResolver().query(
971 ProviderTableMeta
.CONTENT_URI_SHARE
,
973 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
974 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
975 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
976 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
980 c
= getContentProviderClient().query(
981 ProviderTableMeta
.CONTENT_URI_SHARE
,
983 ProviderTableMeta
.OCSHARES_PATH
+ "=? AND "
984 + ProviderTableMeta
.OCSHARES_SHARE_TYPE
+ "=? AND "
985 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
986 new String
[]{path
, Integer
.toString(type
.getValue()), mAccount
.name
},
989 } catch (RemoteException e
) {
990 Log_OC
.e(TAG
, "Could not get file details: " + e
.getMessage());
994 OCShare share
= null
;
995 if (c
.moveToFirst()) {
996 share
= createShareInstance(c
);
1002 private OCShare
createShareInstance(Cursor c
) {
1003 OCShare share
= null
;
1005 share
= new OCShare(c
.getString(c
1006 .getColumnIndex(ProviderTableMeta
.OCSHARES_PATH
)));
1007 share
.setId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
._ID
)));
1008 share
.setFileSource(c
.getLong(c
1009 .getColumnIndex(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
)));
1010 share
.setShareType(ShareType
.fromValue(c
.getInt(c
1011 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_TYPE
))));
1012 share
.setPermissions(c
.getInt(c
1013 .getColumnIndex(ProviderTableMeta
.OCSHARES_PERMISSIONS
)));
1014 share
.setSharedDate(c
.getLong(c
1015 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARED_DATE
)));
1016 share
.setExpirationDate(c
.getLong(c
1017 .getColumnIndex(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
)));
1018 share
.setToken(c
.getString(c
1019 .getColumnIndex(ProviderTableMeta
.OCSHARES_TOKEN
)));
1020 share
.setSharedWithDisplayName(c
.getString(c
1021 .getColumnIndex(ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
)));
1022 share
.setIsFolder(c
.getInt(
1023 c
.getColumnIndex(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
)) == 1);
1024 share
.setUserId(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_USER_ID
)));
1025 share
.setIdRemoteShared(c
.getLong(c
.getColumnIndex(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
)));
1030 private boolean shareExists(String cmp_key
, String value
) {
1032 if (getContentResolver() != null
) {
1033 c
= getContentResolver()
1034 .query(ProviderTableMeta
.CONTENT_URI_SHARE
,
1037 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
1039 new String
[]{value
, mAccount
.name
}, null
);
1042 c
= getContentProviderClient().query(
1043 ProviderTableMeta
.CONTENT_URI_SHARE
,
1046 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?",
1047 new String
[]{value
, mAccount
.name
}, null
);
1048 } catch (RemoteException e
) {
1050 "Couldn't determine file existance, assuming non existance: "
1055 boolean retval
= c
.moveToFirst();
1060 private boolean shareExists(long remoteId
) {
1061 return shareExists(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, String
.valueOf(remoteId
));
1064 private void cleanSharedFiles() {
1065 ContentValues cv
= new ContentValues();
1066 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1067 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1068 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?";
1069 String
[] whereArgs
= new String
[]{mAccount
.name
};
1071 if (getContentResolver() != null
) {
1072 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1076 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1077 } catch (RemoteException e
) {
1078 Log_OC
.e(TAG
, "Exception in cleanSharedFiles" + e
.getMessage());
1083 private void cleanSharedFilesInFolder(OCFile folder
) {
1084 ContentValues cv
= new ContentValues();
1085 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, false
);
1086 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, "");
1087 String where
= ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1088 ProviderTableMeta
.FILE_PARENT
+ "=?";
1089 String
[] whereArgs
= new String
[] { mAccount
.name
, String
.valueOf(folder
.getFileId()) };
1091 if (getContentResolver() != null
) {
1092 getContentResolver().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1096 getContentProviderClient().update(ProviderTableMeta
.CONTENT_URI
, cv
, where
, whereArgs
);
1097 } catch (RemoteException e
) {
1098 Log_OC
.e(TAG
, "Exception in cleanSharedFilesInFolder " + e
.getMessage());
1103 private void cleanShares() {
1104 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1105 String
[] whereArgs
= new String
[]{mAccount
.name
};
1107 if (getContentResolver() != null
) {
1108 getContentResolver().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1112 getContentProviderClient().delete(ProviderTableMeta
.CONTENT_URI_SHARE
, where
, whereArgs
);
1113 } catch (RemoteException e
) {
1114 Log_OC
.e(TAG
, "Exception in cleanShares" + e
.getMessage());
1119 public void saveShares(Collection
<OCShare
> shares
) {
1121 if (shares
!= null
) {
1122 ArrayList
<ContentProviderOperation
> operations
=
1123 new ArrayList
<ContentProviderOperation
>(shares
.size());
1125 // prepare operations to insert or update files to save in the given folder
1126 for (OCShare share
: shares
) {
1127 ContentValues cv
= new ContentValues();
1128 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1129 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1130 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1131 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1132 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1133 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1134 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1135 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1136 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1138 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1139 share
.getSharedWithDisplayName()
1141 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1142 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1143 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1144 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1146 if (shareExists(share
.getIdRemoteShared())) {
1147 // updating an existing file
1149 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI_SHARE
).
1151 withSelection(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
+ "=?",
1152 new String
[]{String
.valueOf(share
.getIdRemoteShared())})
1155 // adding a new file
1157 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1164 // apply operations in batch
1165 if (operations
.size() > 0) {
1166 @SuppressWarnings("unused")
1167 ContentProviderResult
[] results
= null
;
1168 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1169 " operations to FileContentProvider");
1171 if (getContentResolver() != null
) {
1172 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1174 results
= getContentProviderClient().applyBatch(operations
);
1177 } catch (OperationApplicationException e
) {
1178 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1180 } catch (RemoteException e
) {
1181 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1188 public void updateSharedFiles(Collection
<OCFile
> sharedFiles
) {
1191 if (sharedFiles
!= null
) {
1192 ArrayList
<ContentProviderOperation
> operations
=
1193 new ArrayList
<ContentProviderOperation
>(sharedFiles
.size());
1195 // prepare operations to insert or update files to save in the given folder
1196 for (OCFile file
: sharedFiles
) {
1197 ContentValues cv
= new ContentValues();
1198 cv
.put(ProviderTableMeta
.FILE_MODIFIED
, file
.getModificationTimestamp());
1200 ProviderTableMeta
.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
,
1201 file
.getModificationTimestampAtLastSyncForData()
1203 cv
.put(ProviderTableMeta
.FILE_CREATION
, file
.getCreationTimestamp());
1204 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, file
.getFileLength());
1205 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, file
.getMimetype());
1206 cv
.put(ProviderTableMeta
.FILE_NAME
, file
.getFileName());
1207 cv
.put(ProviderTableMeta
.FILE_PARENT
, file
.getParentId());
1208 cv
.put(ProviderTableMeta
.FILE_PATH
, file
.getRemotePath());
1209 if (!file
.isFolder()) {
1210 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, file
.getStoragePath());
1212 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
1213 cv
.put(ProviderTableMeta
.FILE_LAST_SYNC_DATE
, file
.getLastSyncDateForProperties());
1215 ProviderTableMeta
.FILE_LAST_SYNC_DATE_FOR_DATA
,
1216 file
.getLastSyncDateForData()
1218 cv
.put(ProviderTableMeta
.FILE_KEEP_IN_SYNC
, file
.isFavorite() ?
1 : 0);
1219 cv
.put(ProviderTableMeta
.FILE_ETAG
, file
.getEtag());
1220 cv
.put(ProviderTableMeta
.FILE_SHARE_BY_LINK
, file
.isShareByLink() ?
1 : 0);
1221 cv
.put(ProviderTableMeta
.FILE_PUBLIC_LINK
, file
.getPublicLink());
1222 cv
.put(ProviderTableMeta
.FILE_PERMISSIONS
, file
.getPermissions());
1223 cv
.put(ProviderTableMeta
.FILE_REMOTE_ID
, file
.getRemoteId());
1225 ProviderTableMeta
.FILE_UPDATE_THUMBNAIL
,
1226 file
.needsUpdateThumbnail() ?
1 : 0
1229 ProviderTableMeta
.FILE_IS_DOWNLOADING
,
1230 file
.isDownloading() ?
1 : 0
1232 cv
.put(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
, file
.getEtagInConflict());
1234 boolean existsByPath
= fileExists(file
.getRemotePath());
1235 if (existsByPath
|| fileExists(file
.getFileId())) {
1236 // updating an existing file
1238 ContentProviderOperation
.newUpdate(ProviderTableMeta
.CONTENT_URI
).
1240 withSelection(ProviderTableMeta
._ID
+ "=?",
1241 new String
[]{String
.valueOf(file
.getFileId())})
1245 // adding a new file
1247 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI
).
1254 // apply operations in batch
1255 if (operations
.size() > 0) {
1256 @SuppressWarnings("unused")
1257 ContentProviderResult
[] results
= null
;
1258 Log_OC
.d(TAG
, "Sending " + operations
.size() +
1259 " operations to FileContentProvider");
1261 if (getContentResolver() != null
) {
1262 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1264 results
= getContentProviderClient().applyBatch(operations
);
1267 } catch (OperationApplicationException e
) {
1268 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1270 } catch (RemoteException e
) {
1271 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1278 public void removeShare(OCShare share
) {
1279 Uri share_uri
= ProviderTableMeta
.CONTENT_URI_SHARE
;
1280 String where
= ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?" + " AND " +
1281 ProviderTableMeta
.FILE_PATH
+ "=?";
1282 String
[] whereArgs
= new String
[]{mAccount
.name
, share
.getPath()};
1283 if (getContentProviderClient() != null
) {
1285 getContentProviderClient().delete(share_uri
, where
, whereArgs
);
1286 } catch (RemoteException e
) {
1287 e
.printStackTrace();
1290 getContentResolver().delete(share_uri
, where
, whereArgs
);
1294 public void saveSharesDB(ArrayList
<OCShare
> shares
) {
1297 ArrayList
<OCFile
> sharedFiles
= new ArrayList
<OCFile
>();
1299 for (OCShare share
: shares
) {
1301 String path
= share
.getPath();
1302 if (share
.isFolder()) {
1303 path
= path
+ FileUtils
.PATH_SEPARATOR
;
1306 // Update OCFile with data from share: ShareByLink and publicLink
1307 OCFile file
= getFileByPath(path
);
1309 if (share
.getShareType().equals(ShareType
.PUBLIC_LINK
)) {
1310 file
.setShareByLink(true
);
1311 sharedFiles
.add(file
);
1316 updateSharedFiles(sharedFiles
);
1320 public void saveSharesInFolder(ArrayList
<OCShare
> shares
, OCFile folder
) {
1321 cleanSharedFilesInFolder(folder
);
1322 ArrayList
<ContentProviderOperation
> operations
= new ArrayList
<ContentProviderOperation
>();
1323 operations
= prepareRemoveSharesInFolder(folder
, operations
);
1325 if (shares
!= null
) {
1326 // prepare operations to insert or update files to save in the given folder
1327 for (OCShare share
: shares
) {
1328 ContentValues cv
= new ContentValues();
1329 cv
.put(ProviderTableMeta
.OCSHARES_FILE_SOURCE
, share
.getFileSource());
1330 cv
.put(ProviderTableMeta
.OCSHARES_ITEM_SOURCE
, share
.getItemSource());
1331 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_TYPE
, share
.getShareType().getValue());
1332 cv
.put(ProviderTableMeta
.OCSHARES_SHARE_WITH
, share
.getShareWith());
1333 cv
.put(ProviderTableMeta
.OCSHARES_PATH
, share
.getPath());
1334 cv
.put(ProviderTableMeta
.OCSHARES_PERMISSIONS
, share
.getPermissions());
1335 cv
.put(ProviderTableMeta
.OCSHARES_SHARED_DATE
, share
.getSharedDate());
1336 cv
.put(ProviderTableMeta
.OCSHARES_EXPIRATION_DATE
, share
.getExpirationDate());
1337 cv
.put(ProviderTableMeta
.OCSHARES_TOKEN
, share
.getToken());
1339 ProviderTableMeta
.OCSHARES_SHARE_WITH_DISPLAY_NAME
,
1340 share
.getSharedWithDisplayName()
1342 cv
.put(ProviderTableMeta
.OCSHARES_IS_DIRECTORY
, share
.isFolder() ?
1 : 0);
1343 cv
.put(ProviderTableMeta
.OCSHARES_USER_ID
, share
.getUserId());
1344 cv
.put(ProviderTableMeta
.OCSHARES_ID_REMOTE_SHARED
, share
.getIdRemoteShared());
1345 cv
.put(ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
, mAccount
.name
);
1348 if (shareExists(share.getIdRemoteShared())) {
1349 // updating an existing share resource
1351 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1353 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1354 new String[] { String.valueOf(share.getIdRemoteShared()) })
1359 // adding a new share resource
1361 ContentProviderOperation
.newInsert(ProviderTableMeta
.CONTENT_URI_SHARE
).
1369 // apply operations in batch
1370 if (operations
.size() > 0) {
1371 @SuppressWarnings("unused")
1372 ContentProviderResult
[] results
= null
;
1373 Log_OC
.d(TAG
, "Sending " + operations
.size() + " operations to FileContentProvider");
1375 if (getContentResolver() != null
) {
1376 results
= getContentResolver().applyBatch(MainApp
.getAuthority(), operations
);
1379 results
= getContentProviderClient().applyBatch(operations
);
1382 } catch (OperationApplicationException e
) {
1383 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1385 } catch (RemoteException e
) {
1386 Log_OC
.e(TAG
, "Exception in batch of operations " + e
.getMessage());
1393 private ArrayList
<ContentProviderOperation
> prepareRemoveSharesInFolder(
1394 OCFile folder
, ArrayList
<ContentProviderOperation
> preparedOperations
) {
1395 if (folder
!= null
) {
1396 String where
= ProviderTableMeta
.OCSHARES_PATH
+ "=?" + " AND "
1397 + ProviderTableMeta
.OCSHARES_ACCOUNT_OWNER
+ "=?";
1398 String
[] whereArgs
= new String
[]{ "", mAccount
.name
};
1400 Vector
<OCFile
> files
= getFolderContent(folder
, false
);
1402 for (OCFile file
: files
) {
1403 whereArgs
[0] = file
.getRemotePath();
1404 preparedOperations
.add(
1405 ContentProviderOperation
.newDelete(ProviderTableMeta
.CONTENT_URI_SHARE
).
1406 withSelection(where
, whereArgs
).
1411 return preparedOperations
;
1414 public static void triggerMediaScan(String path
) {
1415 Intent intent
= new Intent(Intent
.ACTION_MEDIA_SCANNER_SCAN_FILE
);
1416 intent
.setData(Uri
.fromFile(new File(path
)));
1417 MainApp
.getAppContext().sendBroadcast(intent
);
1420 public void deleteFileInMediaScan(String path
) {
1422 String mimetypeString
= FileStorageUtils
.getMimeTypeFromName(path
);
1423 ContentResolver contentResolver
= getContentResolver();
1425 if (contentResolver
!= null
) {
1426 if (mimetypeString
.startsWith("image/")) {
1428 contentResolver
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1429 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1430 } else if (mimetypeString
.startsWith("audio/")) {
1432 contentResolver
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1433 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1434 } else if (mimetypeString
.startsWith("video/")) {
1436 contentResolver
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1437 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1440 ContentProviderClient contentProviderClient
= getContentProviderClient();
1442 if (mimetypeString
.startsWith("image/")) {
1444 contentProviderClient
.delete(MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
,
1445 MediaStore
.Images
.Media
.DATA
+ "=?", new String
[]{path
});
1446 } else if (mimetypeString
.startsWith("audio/")) {
1448 contentProviderClient
.delete(MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
,
1449 MediaStore
.Audio
.Media
.DATA
+ "=?", new String
[]{path
});
1450 } else if (mimetypeString
.startsWith("video/")) {
1452 contentProviderClient
.delete(MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
,
1453 MediaStore
.Video
.Media
.DATA
+ "=?", new String
[]{path
});
1455 } catch (RemoteException e
) {
1456 Log_OC
.e(TAG
, "Exception deleting media file in MediaStore " + e
.getMessage());
1462 public void saveConflict(OCFile file
, String etagInConflict
) {
1463 if (!file
.isDown()) {
1464 etagInConflict
= null
;
1466 ContentValues cv
= new ContentValues();
1467 cv
.put(ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
, etagInConflict
);
1469 if (getContentResolver() != null
) {
1470 updated
= getContentResolver().update(
1471 ProviderTableMeta
.CONTENT_URI_FILE
,
1473 ProviderTableMeta
._ID
+ "=?",
1474 new String
[] { String
.valueOf(file
.getFileId())}
1478 updated
= getContentProviderClient().update(
1479 ProviderTableMeta
.CONTENT_URI_FILE
,
1481 ProviderTableMeta
._ID
+ "=?",
1482 new String
[]{String
.valueOf(file
.getFileId())}
1484 } catch (RemoteException e
) {
1485 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1489 Log_OC
.d(TAG
, "Number of files updated with CONFLICT: " + updated
);
1492 if (etagInConflict
!= null
) {
1493 /// set conflict in all ancestor folders
1495 long parentId
= file
.getParentId();
1496 Set
<String
> ancestorIds
= new HashSet
<String
>();
1497 while (parentId
!= FileDataStorageManager
.ROOT_PARENT_ID
) {
1498 ancestorIds
.add(Long
.toString(parentId
));
1499 parentId
= getFileById(parentId
).getParentId();
1502 if (ancestorIds
.size() > 0) {
1503 StringBuffer whereBuffer
= new StringBuffer();
1504 whereBuffer
.append(ProviderTableMeta
._ID
).append(" IN (");
1505 for (int i
= 0; i
< ancestorIds
.size() - 1; i
++) {
1506 whereBuffer
.append("?,");
1508 whereBuffer
.append("?");
1509 whereBuffer
.append(")");
1511 if (getContentResolver() != null
) {
1512 updated
= getContentResolver().update(
1513 ProviderTableMeta
.CONTENT_URI_FILE
,
1515 whereBuffer
.toString(),
1516 ancestorIds
.toArray(new String
[]{})
1520 updated
= getContentProviderClient().update(
1521 ProviderTableMeta
.CONTENT_URI_FILE
,
1523 whereBuffer
.toString(),
1524 ancestorIds
.toArray(new String
[]{})
1526 } catch (RemoteException e
) {
1527 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1530 } // else file is ROOT folder, no parent to set in conflict
1533 /// update conflict in ancestor folders
1534 // (not directly unset; maybe there are more conflicts below them)
1535 String parentPath
= file
.getRemotePath();
1536 if (parentPath
.endsWith(OCFile
.PATH_SEPARATOR
)) {
1537 parentPath
= parentPath
.substring(0, parentPath
.length() - 1);
1539 parentPath
= parentPath
.substring(0, parentPath
.lastIndexOf(OCFile
.PATH_SEPARATOR
) + 1);
1541 Log_OC
.d(TAG
, "checking parents to remove conflict; STARTING with " + parentPath
);
1542 while (parentPath
.length() > 0) {
1545 ProviderTableMeta
.FILE_ETAG_IN_CONFLICT
+ " IS NOT NULL AND " +
1546 ProviderTableMeta
.FILE_CONTENT_TYPE
+ " != 'DIR' AND " +
1547 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ " = ? AND " +
1548 ProviderTableMeta
.FILE_PATH
+ " LIKE ?";
1549 Cursor descendentsInConflict
= getContentResolver().query(
1550 ProviderTableMeta
.CONTENT_URI_FILE
,
1551 new String
[]{ProviderTableMeta
._ID
},
1553 new String
[]{mAccount
.name
, parentPath
+ "%"},
1556 if (descendentsInConflict
== null
|| descendentsInConflict
.getCount() == 0) {
1557 Log_OC
.d(TAG
, "NO MORE conflicts in " + parentPath
);
1558 if (getContentResolver() != null
) {
1559 updated
= getContentResolver().update(
1560 ProviderTableMeta
.CONTENT_URI_FILE
,
1562 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1563 ProviderTableMeta
.FILE_PATH
+ "=?",
1564 new String
[]{mAccount
.name
, parentPath
}
1568 updated
= getContentProviderClient().update(
1569 ProviderTableMeta
.CONTENT_URI_FILE
,
1571 ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND " +
1572 ProviderTableMeta
.FILE_PATH
+ "=?"
1573 , new String
[]{mAccount
.name
, parentPath
}
1575 } catch (RemoteException e
) {
1576 Log_OC
.e(TAG
, "Failed saving conflict in database " + e
.getMessage());
1581 Log_OC
.d(TAG
, "STILL " + descendentsInConflict
.getCount() + " in " + parentPath
);
1584 if (descendentsInConflict
!= null
) {
1585 descendentsInConflict
.close();
1588 parentPath
= parentPath
.substring(0, parentPath
.length() - 1); // trim last /
1589 parentPath
= parentPath
.substring(0, parentPath
.lastIndexOf(OCFile
.PATH_SEPARATOR
) + 1);
1590 Log_OC
.d(TAG
, "checking parents to remove conflict; NEXT " + parentPath
);