2  *   ownCloud Android client application 
   4  *   @author David A. Velasco 
   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
.operations
; 
  24 import java
.util
.ArrayList
; 
  25 import java
.util
.HashMap
; 
  26 import java
.util
.List
; 
  28 import java
.util
.Vector
; 
  30 import android
.accounts
.Account
; 
  31 import android
.content
.Context
; 
  32 import android
.content
.Intent
; 
  33 import android
.util
.Log
; 
  36 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
; 
  37 import com
.owncloud
.android
.datamodel
.OCFile
; 
  38 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  39 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
; 
  40 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
; 
  41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  42 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
; 
  43 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
; 
  44 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
; 
  45 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
; 
  46 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
; 
  47 import com
.owncloud
.android
.operations
.common
.SyncOperation
; 
  48 import com
.owncloud
.android
.services
.OperationsService
; 
  49 import com
.owncloud
.android
.utils
.FileStorageUtils
; 
  51 import java
.util
.concurrent
.atomic
.AtomicBoolean
; 
  53 //import android.support.v4.content.LocalBroadcastManager; 
  57  *  Remote operation performing the synchronization of the list of files contained  
  58  *  in a folder identified with its remote path. 
  60  *  Fetches the list and properties of the files contained in the given folder, including their  
  61  *  properties, and updates the local database with them. 
  63  *  Does NOT enter in the child folders to synchronize their contents also. 
  65 public class SynchronizeFolderOperation 
extends SyncOperation 
{ 
  67     private static final String TAG 
= SynchronizeFolderOperation
.class.getSimpleName(); 
  69     /** Time stamp for the synchronization process in progress */ 
  70     private long mCurrentSyncTime
; 
  72     /** Remote path of the folder to synchronize */ 
  73     private String mRemotePath
; 
  75     /** Account where the file to synchronize belongs */ 
  76     private Account mAccount
; 
  78     /** Android context; necessary to send requests to the download service */ 
  79     private Context mContext
; 
  81     /** Locally cached information about folder to synchronize */ 
  82     private OCFile mLocalFolder
; 
  84     /** Files and folders contained in the synchronized folder after a successful operation */ 
  85     //private List<OCFile> mChildren; 
  87     /** Counter of conflicts found between local and remote files */ 
  88     private int mConflictsFound
; 
  90     /** Counter of failed operations in synchronization of kept-in-sync files */ 
  91     private int mFailsInFileSyncsFound
; 
  93     /** 'True' means that the remote folder changed and should be fetched */ 
  94     private boolean mRemoteFolderChanged
; 
  96     private List
<OCFile
> mFilesForDirectDownload
; 
  97         // to avoid extra PROPFINDs when there was no change in the folder 
  99     private List
<SyncOperation
> mFilesToSyncContentsWithoutUpload
; 
 100         // this will go out when 'folder synchronization' replaces 'folder download'; step by step   
 102     private List
<SyncOperation
> mFavouriteFilesToSyncContents
; 
 103         // this will be used for every file when 'folder synchronization' replaces 'folder download'  
 105     private final AtomicBoolean mCancellationRequested
; 
 108      * Creates a new instance of {@link SynchronizeFolderOperation}. 
 110      * @param   context                 Application context. 
 111      * @param   remotePath              Path to synchronize. 
 112      * @param   account                 ownCloud account where the folder is located. 
 113      * @param   currentSyncTime         Time stamp for the synchronization process in progress. 
 115     public SynchronizeFolderOperation(Context context
, String remotePath
, Account account
, 
 116                                       long currentSyncTime
){ 
 117         mRemotePath 
= remotePath
; 
 118         mCurrentSyncTime 
= currentSyncTime
; 
 121         mRemoteFolderChanged 
= false
; 
 122         mFilesForDirectDownload 
= new Vector
<OCFile
>(); 
 123         mFilesToSyncContentsWithoutUpload 
= new Vector
<SyncOperation
>(); 
 124         mFavouriteFilesToSyncContents 
= new Vector
<SyncOperation
>(); 
 125         mCancellationRequested 
= new AtomicBoolean(false
); 
 129     public int getConflictsFound() { 
 130         return mConflictsFound
; 
 133     public int getFailsInFileSyncsFound() { 
 134         return mFailsInFileSyncsFound
; 
 138      * Performs the synchronization. 
 143     protected RemoteOperationResult 
run(OwnCloudClient client
) { 
 144         RemoteOperationResult result 
= null
; 
 145         mFailsInFileSyncsFound 
= 0; 
 149             // get locally cached information about folder  
 150             mLocalFolder 
= getStorageManager().getFileByPath(mRemotePath
);    
 152             result 
= checkForChanges(client
); 
 154             if (result
.isSuccess()) { 
 155                 if (mRemoteFolderChanged
) { 
 156                     result 
= fetchAndSyncRemoteFolder(client
); 
 159                     prepareOpsFromLocalKnowledge(); 
 162                 if (result
.isSuccess()) { 
 163                     syncContents(client
); 
 168             if (mCancellationRequested
.get()) { 
 169                 throw new OperationCancelledException(); 
 172         } catch (OperationCancelledException e
) { 
 173             result 
= new RemoteOperationResult(e
); 
 180     private RemoteOperationResult 
checkForChanges(OwnCloudClient client
) 
 181             throws OperationCancelledException 
{ 
 182         Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name 
+ mRemotePath
); 
 184         mRemoteFolderChanged 
= true
; 
 185         RemoteOperationResult result 
= null
; 
 187         if (mCancellationRequested
.get()) { 
 188             throw new OperationCancelledException(); 
 192         ReadRemoteFileOperation operation 
= new ReadRemoteFileOperation(mRemotePath
); 
 193         result 
= operation
.execute(client
); 
 194         if (result
.isSuccess()){ 
 195             OCFile remoteFolder 
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0)); 
 197             // check if remote and local folder are different 
 198             mRemoteFolderChanged 
= 
 199                         !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag())); 
 201             result 
= new RemoteOperationResult(ResultCode
.OK
); 
 203             Log_OC
.i(TAG
, "Checked " + mAccount
.name 
+ mRemotePath 
+ " : " + 
 204                     (mRemoteFolderChanged ? 
"changed" : "not changed")); 
 208             if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) { 
 211             if (result
.isException()) { 
 212                 Log_OC
.e(TAG
, "Checked " + mAccount
.name 
+ mRemotePath  
+ " : " + 
 213                         result
.getLogMessage(), result
.getException()); 
 215                 Log_OC
.e(TAG
, "Checked " + mAccount
.name 
+ mRemotePath 
+ " : " + 
 216                         result
.getLogMessage()); 
 225     private RemoteOperationResult 
fetchAndSyncRemoteFolder(OwnCloudClient client
) 
 226             throws OperationCancelledException 
{ 
 227         if (mCancellationRequested
.get()) { 
 228             throw new OperationCancelledException(); 
 231         ReadRemoteFolderOperation operation 
= new ReadRemoteFolderOperation(mRemotePath
); 
 232         RemoteOperationResult result 
= operation
.execute(client
); 
 233         Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name 
+ mRemotePath
); 
 235         if (result
.isSuccess()) { 
 236             synchronizeData(result
.getData(), client
); 
 237             if (mConflictsFound 
> 0  || mFailsInFileSyncsFound 
> 0) { 
 238                 result 
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); 
 239                     // should be a different result code, but will do the job 
 242             if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) 
 251     private void removeLocalFolder() { 
 252         FileDataStorageManager storageManager 
= getStorageManager(); 
 253         if (storageManager
.fileExists(mLocalFolder
.getFileId())) { 
 254             String currentSavePath 
= FileStorageUtils
.getSavePath(mAccount
.name
); 
 255             storageManager
.removeFolder( 
 258                     (   mLocalFolder
.isDown() &&        // TODO: debug, I think this is 
 259                                                         // always false for folders 
 260                             mLocalFolder
.getStoragePath().startsWith(currentSavePath
) 
 268      *  Synchronizes the data retrieved from the server about the contents of the target folder 
 269      *  with the current data in the local database. 
 271      *  Grants that mChildren is updated with fresh data after execution. 
 273      *  @param folderAndFiles   Remote folder and children files in Folder 
 275      *  @param client           Client instance to the remote server where the data were 
 277      *  @return                 'True' when any change was made in the local data, 'false' otherwise 
 279     private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) 
 280             throws OperationCancelledException 
{ 
 281         FileDataStorageManager storageManager 
= getStorageManager(); 
 283         // parse data from remote folder 
 284         OCFile remoteFolder 
= fillOCFile((RemoteFile
)folderAndFiles
.get(0)); 
 285         remoteFolder
.setParentId(mLocalFolder
.getParentId()); 
 286         remoteFolder
.setFileId(mLocalFolder
.getFileId()); 
 288         Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() 
 289                 + " changed - starting update of local data "); 
 291         List
<OCFile
> updatedFiles 
= new Vector
<OCFile
>(folderAndFiles
.size() - 1); 
 292         mFilesForDirectDownload
.clear(); 
 293         mFilesToSyncContentsWithoutUpload
.clear(); 
 294         mFavouriteFilesToSyncContents
.clear(); 
 296         if (mCancellationRequested
.get()) { 
 297             throw new OperationCancelledException(); 
 300         // get current data about local contents of the folder to synchronize 
 301         // TODO Enable when "On Device" is recovered ? 
 302         List
<OCFile
> localFiles 
= storageManager
.getFolderContent(mLocalFolder
/*, false*/); 
 303         Map
<String
, OCFile
> localFilesMap 
= new HashMap
<String
, OCFile
>(localFiles
.size()); 
 304         for (OCFile file 
: localFiles
) { 
 305             localFilesMap
.put(file
.getRemotePath(), file
); 
 308         // loop to synchronize every child 
 309         OCFile remoteFile 
= null
, localFile 
= null
; 
 310         for (int i
=1; i
<folderAndFiles
.size(); i
++) { 
 311             /// new OCFile instance with the data from the server 
 312             remoteFile 
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
)); 
 313             remoteFile
.setParentId(mLocalFolder
.getFileId()); 
 315             /// retrieve local data for the read file 
 316             //  localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath()); 
 317             localFile 
= localFilesMap
.remove(remoteFile
.getRemotePath()); 
 319             /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server) 
 320             remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
); 
 321             if (localFile 
!= null
) { 
 322                 // some properties of local state are kept unmodified 
 323                 remoteFile
.setFileId(localFile
.getFileId()); 
 324                 remoteFile
.setFavorite(localFile
.isFavorite()); 
 325                 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData()); 
 326                 remoteFile
.setModificationTimestampAtLastSyncForData( 
 327                         localFile
.getModificationTimestampAtLastSyncForData() 
 329                 remoteFile
.setStoragePath(localFile
.getStoragePath()); 
 330                 // eTag will not be updated unless contents are synchronized 
 331                 //  (Synchronize[File|Folder]Operation with remoteFile as parameter) 
 332                 remoteFile
.setEtag(localFile
.getEtag()); 
 333                 if (remoteFile
.isFolder()) { 
 334                     remoteFile
.setFileLength(localFile
.getFileLength()); 
 335                         // TODO move operations about size of folders to FileContentProvider 
 336                 } else if (mRemoteFolderChanged 
&& remoteFile
.isImage() && 
 337                         remoteFile
.getModificationTimestamp() != 
 338                                 localFile
.getModificationTimestamp()) { 
 339                     remoteFile
.setNeedsUpdateThumbnail(true
); 
 340                     Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server"); 
 342                 remoteFile
.setPublicLink(localFile
.getPublicLink()); 
 343                 remoteFile
.setShareByLink(localFile
.isShareByLink()); 
 345                 // remote eTag will not be updated unless contents are synchronized 
 346                 //  (Synchronize[File|Folder]Operation with remoteFile as parameter) 
 347                 remoteFile
.setEtag(""); 
 350             /// check and fix, if needed, local storage path 
 351             searchForLocalFileInDefaultPath(remoteFile
); 
 353             /// classify file to sync/download contents later 
 354             if (remoteFile
.isFolder()) { 
 355                 /// to download children files recursively 
 356                 synchronized(mCancellationRequested
) { 
 357                     if (mCancellationRequested
.get()) { 
 358                         throw new OperationCancelledException(); 
 360                     startSyncFolderOperation(remoteFile
.getRemotePath()); 
 363             } else if (remoteFile
.isFavorite()) { 
 364                 /// prepare content synchronization for kept-in-sync files 
 365                 SynchronizeFileOperation operation 
= new SynchronizeFileOperation( 
 372                 mFavouriteFilesToSyncContents
.add(operation
); 
 375                 /// prepare limited synchronization for regular files 
 376                 SynchronizeFileOperation operation 
= new SynchronizeFileOperation( 
 384                 mFilesToSyncContentsWithoutUpload
.add(operation
); 
 387             updatedFiles
.add(remoteFile
); 
 390         // save updated contents in local database 
 391         storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values()); 
 396     private void prepareOpsFromLocalKnowledge() throws OperationCancelledException 
{ 
 397         // TODO Enable when "On Device" is recovered ? 
 398         List
<OCFile
> children 
= getStorageManager().getFolderContent(mLocalFolder
/*, false*/); 
 399         for (OCFile child 
: children
) { 
 400             /// classify file to sync/download contents later 
 401             if (child
.isFolder()) { 
 402                 /// to download children files recursively 
 403                 synchronized(mCancellationRequested
) { 
 404                     if (mCancellationRequested
.get()) { 
 405                         throw new OperationCancelledException(); 
 407                     startSyncFolderOperation(child
.getRemotePath()); 
 411                 /// prepare limited synchronization for regular files 
 412                 if (!child
.isDown()) { 
 413                     mFilesForDirectDownload
.add(child
); 
 420     private void syncContents(OwnCloudClient client
) throws OperationCancelledException 
{ 
 421         startDirectDownloads(); 
 422         startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
); 
 423         startContentSynchronizations(mFavouriteFilesToSyncContents
, client
); 
 427     private void startDirectDownloads() throws OperationCancelledException 
{ 
 428         for (OCFile file 
: mFilesForDirectDownload
) { 
 429             synchronized(mCancellationRequested
) { 
 430                 if (mCancellationRequested
.get()) { 
 431                     throw new OperationCancelledException(); 
 433                 Intent i 
= new Intent(mContext
, FileDownloader
.class); 
 434                 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
); 
 435                 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
 436                 mContext
.startService(i
); 
 442      * Performs a list of synchronization operations, determining if a download or upload is needed 
 443      * or if exists conflict due to changes both in local and remote contents of the each file. 
 445      * If download or upload is needed, request the operation to the corresponding service and goes 
 448      * @param filesToSyncContents       Synchronization operations to execute. 
 449      * @param client                    Interface to the remote ownCloud server. 
 451     private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, 
 452                                               OwnCloudClient client
) 
 453             throws OperationCancelledException 
{ 
 455         Log_OC
.v(TAG
, "Starting content synchronization... "); 
 456         RemoteOperationResult contentsResult 
= null
; 
 457         for (SyncOperation op
: filesToSyncContents
) { 
 458             if (mCancellationRequested
.get()) { 
 459                 throw new OperationCancelledException(); 
 461             contentsResult 
= op
.execute(getStorageManager(), mContext
); 
 462             if (!contentsResult
.isSuccess()) { 
 463                 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) { 
 466                     mFailsInFileSyncsFound
++; 
 467                     if (contentsResult
.getException() != null
) { 
 468                         Log_OC
.e(TAG
, "Error while synchronizing file : " 
 469                                 +  contentsResult
.getLogMessage(), contentsResult
.getException()); 
 471                         Log_OC
.e(TAG
, "Error while synchronizing file : " 
 472                                 + contentsResult
.getLogMessage()); 
 475                 // TODO - use the errors count in notifications 
 476             }   // won't let these fails break the synchronization process 
 482      * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} 
 483      * object with the data read from the server. 
 485      * @param remote    remote file read from the server (remote file or folder). 
 486      * @return          New OCFile instance representing the remote resource described by we. 
 488     private OCFile 
fillOCFile(RemoteFile remote
) { 
 489         OCFile file 
= new OCFile(remote
.getRemotePath()); 
 490         file
.setCreationTimestamp(remote
.getCreationTimestamp()); 
 491         file
.setFileLength(remote
.getLength()); 
 492         file
.setMimetype(remote
.getMimeType()); 
 493         file
.setModificationTimestamp(remote
.getModifiedTimestamp()); 
 494         file
.setEtag(remote
.getEtag()); 
 495         file
.setPermissions(remote
.getPermissions()); 
 496         file
.setRemoteId(remote
.getRemoteId()); 
 502      * Scans the default location for saving local copies of files searching for 
 503      * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} 
 504      * received as parameter. 
 506      * @param file      File to associate a possible 'lost' local file. 
 508     private void searchForLocalFileInDefaultPath(OCFile file
) { 
 509         if (file
.getStoragePath() == null 
&& !file
.isFolder()) { 
 510             File f 
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
)); 
 512                 file
.setStoragePath(f
.getAbsolutePath()); 
 513                 file
.setLastSyncDateForData(f
.lastModified()); 
 522     public void cancel() { 
 523         mCancellationRequested
.set(true
); 
 526     public String 
getFolderPath() { 
 527         String path 
= mLocalFolder
.getStoragePath(); 
 528         if (path 
!= null 
&& path
.length() > 0) { 
 531         return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
); 
 534     private void startSyncFolderOperation(String path
){ 
 535         Intent intent 
= new Intent(mContext
, OperationsService
.class); 
 536         intent
.setAction(OperationsService
.ACTION_SYNC_FOLDER
); 
 537         intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, mAccount
); 
 538         intent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, path
); 
 539         mContext
.startService(intent
); 
 542     public String 
getRemotePath() {