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
; 
  23 import android
.accounts
.Account
; 
  24 import android
.content
.Context
; 
  25 import android
.content
.Intent
; 
  26 import android
.util
.Log
; 
  28 import com
.owncloud
.android
.MainApp
; 
  29 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
; 
  30 import com
.owncloud
.android
.datamodel
.OCFile
; 
  31 import com
.owncloud
.android
.files
.services
.FileDownloader
; 
  32 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
; 
  33 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
; 
  34 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
; 
  35 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
; 
  36 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
; 
  37 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
; 
  38 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
; 
  39 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
; 
  40 import com
.owncloud
.android
.operations
.common
.SyncOperation
; 
  41 import com
.owncloud
.android
.services
.OperationsService
; 
  42 import com
.owncloud
.android
.utils
.FileStorageUtils
; 
  45 import java
.util
.ArrayList
; 
  46 import java
.util
.HashMap
; 
  47 import java
.util
.List
; 
  49 import java
.util
.Vector
; 
  50 import java
.util
.concurrent
.atomic
.AtomicBoolean
; 
  52 //import android.support.v4.content.LocalBroadcastManager; 
  56  *  Remote operation performing the synchronization of the list of files contained  
  57  *  in a folder identified with its remote path. 
  59  *  Fetches the list and properties of the files contained in the given folder, including their  
  60  *  properties, and updates the local database with them. 
  62  *  Does NOT enter in the child folders to synchronize their contents also. 
  64 public class SynchronizeFolderOperation 
extends SyncOperation 
{ 
  66     private static final String TAG 
= SynchronizeFolderOperation
.class.getSimpleName(); 
  68     /** Time stamp for the synchronization process in progress */ 
  69     private long mCurrentSyncTime
; 
  71     /** Remote path of the folder to synchronize */ 
  72     private String mRemotePath
; 
  74     /** Account where the file to synchronize belongs */ 
  75     private Account mAccount
; 
  77     /** Android context; necessary to send requests to the download service */ 
  78     private Context mContext
; 
  80     /** Locally cached information about folder to synchronize */ 
  81     private OCFile mLocalFolder
; 
  83     /** Files and folders contained in the synchronized folder after a successful operation */ 
  84     //private List<OCFile> mChildren; 
  86     /** Counter of conflicts found between local and remote files */ 
  87     private int mConflictsFound
; 
  89     /** Counter of failed operations in synchronization of kept-in-sync files */ 
  90     private int mFailsInFileSyncsFound
; 
  92     /** 'True' means that the remote folder changed and should be fetched */ 
  93     private boolean mRemoteFolderChanged
; 
  95     private List
<OCFile
> mFilesForDirectDownload
; 
  96         // to avoid extra PROPFINDs when there was no change in the folder 
  98     private List
<SyncOperation
> mFilesToSyncContentsWithoutUpload
; 
  99         // this will go out when 'folder synchronization' replaces 'folder download'; step by step   
 101     private List
<SyncOperation
> mFavouriteFilesToSyncContents
; 
 102         // this will be used for every file when 'folder synchronization' replaces 'folder download'  
 104     private final AtomicBoolean mCancellationRequested
; 
 107      * Creates a new instance of {@link SynchronizeFolderOperation}. 
 109      * @param   context                 Application context. 
 110      * @param   remotePath              Path to synchronize. 
 111      * @param   account                 ownCloud account where the folder is located. 
 112      * @param   currentSyncTime         Time stamp for the synchronization process in progress. 
 114     public SynchronizeFolderOperation(Context context
, String remotePath
, Account account
, 
 115                                       long currentSyncTime
){ 
 116         mRemotePath 
= remotePath
; 
 117         mCurrentSyncTime 
= currentSyncTime
; 
 120         mRemoteFolderChanged 
= false
; 
 121         mFilesForDirectDownload 
= new Vector
<OCFile
>(); 
 122         mFilesToSyncContentsWithoutUpload 
= new Vector
<SyncOperation
>(); 
 123         mFavouriteFilesToSyncContents 
= new Vector
<SyncOperation
>(); 
 124         mCancellationRequested 
= new AtomicBoolean(false
); 
 128     public int getConflictsFound() { 
 129         return mConflictsFound
; 
 132     public int getFailsInFileSyncsFound() { 
 133         return mFailsInFileSyncsFound
; 
 137      * Performs the synchronization. 
 142     protected RemoteOperationResult 
run(OwnCloudClient client
) { 
 143         RemoteOperationResult result 
= null
; 
 144         mFailsInFileSyncsFound 
= 0; 
 148             // get locally cached information about folder  
 149             mLocalFolder 
= getStorageManager().getFileByPath(mRemotePath
);    
 151             result 
= checkForChanges(client
); 
 153             if (result
.isSuccess()) { 
 154                 if (mRemoteFolderChanged
) { 
 155                     result 
= fetchAndSyncRemoteFolder(client
); 
 158                     prepareOpsFromLocalKnowledge(); 
 161                 if (result
.isSuccess()) { 
 162                     syncContents(client
); 
 167             if (mCancellationRequested
.get()) { 
 168                 throw new OperationCancelledException(); 
 171         } catch (OperationCancelledException e
) { 
 172             result 
= new RemoteOperationResult(e
); 
 179     private RemoteOperationResult 
checkForChanges(OwnCloudClient client
) 
 180             throws OperationCancelledException 
{ 
 181         Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name 
+ mRemotePath
); 
 183         mRemoteFolderChanged 
= true
; 
 184         RemoteOperationResult result 
= null
; 
 186         if (mCancellationRequested
.get()) { 
 187             throw new OperationCancelledException(); 
 191         ReadRemoteFileOperation operation 
= new ReadRemoteFileOperation(mRemotePath
); 
 192         result 
= operation
.execute(client
, MainApp
.getUserAgent()); 
 193         if (result
.isSuccess()){ 
 194             OCFile remoteFolder 
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0)); 
 196             // check if remote and local folder are different 
 197             mRemoteFolderChanged 
= 
 198                         !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag())); 
 200             result 
= new RemoteOperationResult(ResultCode
.OK
); 
 202             Log_OC
.i(TAG
, "Checked " + mAccount
.name 
+ mRemotePath 
+ " : " + 
 203                     (mRemoteFolderChanged ? 
"changed" : "not changed")); 
 207             if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) { 
 210             if (result
.isException()) { 
 211                 Log_OC
.e(TAG
, "Checked " + mAccount
.name 
+ mRemotePath  
+ " : " + 
 212                         result
.getLogMessage(), result
.getException()); 
 214                 Log_OC
.e(TAG
, "Checked " + mAccount
.name 
+ mRemotePath 
+ " : " + 
 215                         result
.getLogMessage()); 
 224     private RemoteOperationResult 
fetchAndSyncRemoteFolder(OwnCloudClient client
) 
 225             throws OperationCancelledException 
{ 
 226         if (mCancellationRequested
.get()) { 
 227             throw new OperationCancelledException(); 
 230         ReadRemoteFolderOperation operation 
= new ReadRemoteFolderOperation(mRemotePath
); 
 231         RemoteOperationResult result 
= operation
.execute(client
, MainApp
.getUserAgent()); 
 232         Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name 
+ mRemotePath
); 
 234         if (result
.isSuccess()) { 
 235             synchronizeData(result
.getData(), client
); 
 236             if (mConflictsFound 
> 0  || mFailsInFileSyncsFound 
> 0) { 
 237                 result 
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); 
 238                     // should be a different result code, but will do the job 
 241             if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) 
 250     private void removeLocalFolder() { 
 251         FileDataStorageManager storageManager 
= getStorageManager(); 
 252         if (storageManager
.fileExists(mLocalFolder
.getFileId())) { 
 253             String currentSavePath 
= FileStorageUtils
.getSavePath(mAccount
.name
); 
 254             storageManager
.removeFolder( 
 257                     (   mLocalFolder
.isDown() &&        // TODO: debug, I think this is 
 258                                                         // always false for folders 
 259                             mLocalFolder
.getStoragePath().startsWith(currentSavePath
) 
 267      *  Synchronizes the data retrieved from the server about the contents of the target folder 
 268      *  with the current data in the local database. 
 270      *  Grants that mChildren is updated with fresh data after execution. 
 272      *  @param folderAndFiles   Remote folder and children files in Folder 
 274      *  @param client           Client instance to the remote server where the data were 
 276      *  @return                 'True' when any change was made in the local data, 'false' otherwise 
 278     private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) 
 279             throws OperationCancelledException 
{ 
 280         FileDataStorageManager storageManager 
= getStorageManager(); 
 282         // parse data from remote folder 
 283         OCFile remoteFolder 
= fillOCFile((RemoteFile
)folderAndFiles
.get(0)); 
 284         remoteFolder
.setParentId(mLocalFolder
.getParentId()); 
 285         remoteFolder
.setFileId(mLocalFolder
.getFileId()); 
 287         Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() 
 288                 + " changed - starting update of local data "); 
 290         List
<OCFile
> updatedFiles 
= new Vector
<OCFile
>(folderAndFiles
.size() - 1); 
 291         mFilesForDirectDownload
.clear(); 
 292         mFilesToSyncContentsWithoutUpload
.clear(); 
 293         mFavouriteFilesToSyncContents
.clear(); 
 295         if (mCancellationRequested
.get()) { 
 296             throw new OperationCancelledException(); 
 299         // get current data about local contents of the folder to synchronize 
 300         List
<OCFile
> localFiles 
= storageManager
.getFolderContent(mLocalFolder
); 
 301         Map
<String
, OCFile
> localFilesMap 
= new HashMap
<String
, OCFile
>(localFiles
.size()); 
 302         for (OCFile file 
: localFiles
) { 
 303             localFilesMap
.put(file
.getRemotePath(), file
); 
 306         // loop to synchronize every child 
 307         OCFile remoteFile 
= null
, localFile 
= null
; 
 308         for (int i
=1; i
<folderAndFiles
.size(); i
++) { 
 309             /// new OCFile instance with the data from the server 
 310             remoteFile 
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
)); 
 311             remoteFile
.setParentId(mLocalFolder
.getFileId()); 
 313             /// retrieve local data for the read file 
 314             //  localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath()); 
 315             localFile 
= localFilesMap
.remove(remoteFile
.getRemotePath()); 
 317             /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server) 
 318             remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
); 
 319             if (localFile 
!= null
) { 
 320                 // some properties of local state are kept unmodified 
 321                 remoteFile
.setFileId(localFile
.getFileId()); 
 322                 remoteFile
.setKeepInSync(localFile
.keepInSync()); 
 323                 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData()); 
 324                 remoteFile
.setModificationTimestampAtLastSyncForData( 
 325                         localFile
.getModificationTimestampAtLastSyncForData() 
 327                 remoteFile
.setStoragePath(localFile
.getStoragePath()); 
 328                 // eTag will not be updated unless contents are synchronized 
 329                 //  (Synchronize[File|Folder]Operation with remoteFile as parameter) 
 330                 remoteFile
.setEtag(localFile
.getEtag()); 
 331                 if (remoteFile
.isFolder()) { 
 332                     remoteFile
.setFileLength(localFile
.getFileLength()); 
 333                         // TODO move operations about size of folders to FileContentProvider 
 334                 } else if (mRemoteFolderChanged 
&& remoteFile
.isImage() && 
 335                         remoteFile
.getModificationTimestamp() != 
 336                                 localFile
.getModificationTimestamp()) { 
 337                     remoteFile
.setNeedsUpdateThumbnail(true
); 
 338                     Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server"); 
 340                 remoteFile
.setPublicLink(localFile
.getPublicLink()); 
 341                 remoteFile
.setShareByLink(localFile
.isShareByLink()); 
 343                 // remote eTag will not be updated unless contents are synchronized 
 344                 //  (Synchronize[File|Folder]Operation with remoteFile as parameter) 
 345                 remoteFile
.setEtag(""); 
 348             /// check and fix, if needed, local storage path 
 349             searchForLocalFileInDefaultPath(remoteFile
); 
 351             /// classify file to sync/download contents later 
 352             if (remoteFile
.isFolder()) { 
 353                 /// to download children files recursively 
 354                 synchronized(mCancellationRequested
) { 
 355                     if (mCancellationRequested
.get()) { 
 356                         throw new OperationCancelledException(); 
 358                     startSyncFolderOperation(remoteFile
.getRemotePath()); 
 361             } else if (remoteFile
.keepInSync()) { 
 362                 /// prepare content synchronization for kept-in-sync files 
 363                 SynchronizeFileOperation operation 
= new SynchronizeFileOperation( 
 370                 mFavouriteFilesToSyncContents
.add(operation
); 
 373                 /// prepare limited synchronization for regular files 
 374                 SynchronizeFileOperation operation 
= new SynchronizeFileOperation( 
 382                 mFilesToSyncContentsWithoutUpload
.add(operation
); 
 385             updatedFiles
.add(remoteFile
); 
 388         // save updated contents in local database 
 389         storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values()); 
 394     private void prepareOpsFromLocalKnowledge() throws OperationCancelledException 
{ 
 395         List
<OCFile
> children 
= getStorageManager().getFolderContent(mLocalFolder
); 
 396         for (OCFile child 
: children
) { 
 397             /// classify file to sync/download contents later 
 398             if (child
.isFolder()) { 
 399                 /// to download children files recursively 
 400                 synchronized(mCancellationRequested
) { 
 401                     if (mCancellationRequested
.get()) { 
 402                         throw new OperationCancelledException(); 
 404                     startSyncFolderOperation(child
.getRemotePath()); 
 408                 /// prepare limited synchronization for regular files 
 409                 if (!child
.isDown()) { 
 410                     mFilesForDirectDownload
.add(child
); 
 417     private void syncContents(OwnCloudClient client
) throws OperationCancelledException 
{ 
 418         startDirectDownloads(); 
 419         startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
); 
 420         startContentSynchronizations(mFavouriteFilesToSyncContents
, client
); 
 424     private void startDirectDownloads() throws OperationCancelledException 
{ 
 425         for (OCFile file 
: mFilesForDirectDownload
) { 
 426             synchronized(mCancellationRequested
) { 
 427                 if (mCancellationRequested
.get()) { 
 428                     throw new OperationCancelledException(); 
 430                 Intent i 
= new Intent(mContext
, FileDownloader
.class); 
 431                 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
); 
 432                 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
); 
 433                 mContext
.startService(i
); 
 439      * Performs a list of synchronization operations, determining if a download or upload is needed 
 440      * or if exists conflict due to changes both in local and remote contents of the each file. 
 442      * If download or upload is needed, request the operation to the corresponding service and goes 
 445      * @param filesToSyncContents       Synchronization operations to execute. 
 446      * @param client                    Interface to the remote ownCloud server. 
 448     private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, 
 449                                               OwnCloudClient client
) 
 450             throws OperationCancelledException 
{ 
 452         Log_OC
.v(TAG
, "Starting content synchronization... "); 
 453         RemoteOperationResult contentsResult 
= null
; 
 454         for (SyncOperation op
: filesToSyncContents
) { 
 455             if (mCancellationRequested
.get()) { 
 456                 throw new OperationCancelledException(); 
 458             contentsResult 
= op
.execute(getStorageManager(), mContext
); 
 459             if (!contentsResult
.isSuccess()) { 
 460                 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) { 
 463                     mFailsInFileSyncsFound
++; 
 464                     if (contentsResult
.getException() != null
) { 
 465                         Log_OC
.e(TAG
, "Error while synchronizing file : " 
 466                                 +  contentsResult
.getLogMessage(), contentsResult
.getException()); 
 468                         Log_OC
.e(TAG
, "Error while synchronizing file : " 
 469                                 + contentsResult
.getLogMessage()); 
 472                 // TODO - use the errors count in notifications 
 473             }   // won't let these fails break the synchronization process 
 479      * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} 
 480      * object with the data read from the server. 
 482      * @param remote    remote file read from the server (remote file or folder). 
 483      * @return          New OCFile instance representing the remote resource described by we. 
 485     private OCFile 
fillOCFile(RemoteFile remote
) { 
 486         OCFile file 
= new OCFile(remote
.getRemotePath()); 
 487         file
.setCreationTimestamp(remote
.getCreationTimestamp()); 
 488         file
.setFileLength(remote
.getLength()); 
 489         file
.setMimetype(remote
.getMimeType()); 
 490         file
.setModificationTimestamp(remote
.getModifiedTimestamp()); 
 491         file
.setEtag(remote
.getEtag()); 
 492         file
.setPermissions(remote
.getPermissions()); 
 493         file
.setRemoteId(remote
.getRemoteId()); 
 499      * Scans the default location for saving local copies of files searching for 
 500      * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} 
 501      * received as parameter. 
 503      * @param file      File to associate a possible 'lost' local file. 
 505     private void searchForLocalFileInDefaultPath(OCFile file
) { 
 506         if (file
.getStoragePath() == null 
&& !file
.isFolder()) { 
 507             File f 
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
)); 
 509                 file
.setStoragePath(f
.getAbsolutePath()); 
 510                 file
.setLastSyncDateForData(f
.lastModified()); 
 519     public void cancel() { 
 520         mCancellationRequested
.set(true
); 
 523     public String 
getFolderPath() { 
 524         String path 
= mLocalFolder
.getStoragePath(); 
 525         if (path 
!= null 
&& path
.length() > 0) { 
 528         return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
); 
 531     private void startSyncFolderOperation(String path
){ 
 532         Intent intent 
= new Intent(mContext
, OperationsService
.class); 
 533         intent
.setAction(OperationsService
.ACTION_SYNC_FOLDER
); 
 534         intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, mAccount
); 
 535         intent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, path
); 
 536         mContext
.startService(intent
); 
 539     public String 
getRemotePath() {