Browse Source

Synchronize kept-in-sync files during account synchronization, in both directions and considering conflicts

David A. Velasco 12 years ago
parent
commit
c301865c35

+ 4 - 0
res/values/strings.xml

@@ -109,6 +109,10 @@
     <string name="sync_string_contacts">Contacts</string>
 	<string name="sync_fail_ticker">Synchronization failed</string>
     <string name="sync_fail_content">Synchronization of %1$s could not be completed</string>
+	<string name="sync_conflicts_in_favourites_ticker">Conflicts found</string>
+	<string name="sync_conflicts_in_favourites_content">%1$d kept-in-sync files could not be sync\'ed</string>
+    <string name="sync_fail_in_favourites_ticker">Kept-in-sync files failed</string>
+	<string name="sync_fail_in_favourites_content">Contents of %1$d files could not be sync\'ed (%2$d conflicts)</string>
 	<string name="use_ssl">Use Secure Connection</string>
     <string name="location_no_provider">ownCloud cannot track your device. Please check your location settings</string>
     

+ 1 - 1
src/com/owncloud/android/files/OwnCloudFileObserver.java

@@ -101,7 +101,7 @@ public class OwnCloudFileObserver extends FileObserver {
             return;
         }
         WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mOCAccount, mContext);
-        SynchronizeFileOperation sfo = new SynchronizeFileOperation(mFile, mStorage, mOCAccount, true, false, mContext);
+        SynchronizeFileOperation sfo = new SynchronizeFileOperation(mFile, null, mStorage, mOCAccount, true, false, mContext);
         RemoteOperationResult result = sfo.execute(wc);
         for (FileObserverStatusListener l : mListeners) {
             l.onObservedFileStatusUpdate(mPath, getRemotePath(), mOCAccount, result);

+ 18 - 3
src/com/owncloud/android/files/services/FileDownloader.java

@@ -136,6 +136,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             mPendingDownloads.putIfAbsent(downloadKey, newDownload);
             newDownload.addDatatransferProgressListener(this);
             requestedDownloads.add(downloadKey);
+            sendBroadcastNewDownload(newDownload);
             
         } catch (IllegalArgumentException e) {
             Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
@@ -273,7 +274,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             /// notify result
             notifyDownloadResult(mCurrentDownload, downloadResult);
             
-            sendFinalBroadcast(mCurrentDownload, downloadResult);
+            sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
         }
     }
 
@@ -368,12 +369,12 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
     
     
     /**
-     * Sends a broadcast in order to the interested activities can update their view
+     * Sends a broadcast when a download finishes in order to the interested activities can update their view
      * 
      * @param download          Finished download operation
      * @param downloadResult    Result of the download operation
      */
-    private void sendFinalBroadcast(DownloadFileOperation download, RemoteOperationResult downloadResult) {
+    private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
         Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
         end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
         end.putExtra(ACCOUNT_NAME, download.getAccount().name);
@@ -381,5 +382,19 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
         sendBroadcast(end);
     }
+    
+    
+    /**
+     * Sends a broadcast when a new download is added to the queue.
+     * 
+     * @param download          Added download operation
+     */
+    private void sendBroadcastNewDownload(DownloadFileOperation download) {
+        Intent end = new Intent(DOWNLOAD_ADDED_MESSAGE);
+        /*end.putExtra(ACCOUNT_NAME, download.getAccount().name);
+        end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());*/
+        end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
+        sendBroadcast(end);
+    }
 
 }

+ 93 - 135
src/com/owncloud/android/files/services/FileObserverService.java

@@ -19,8 +19,8 @@
 package com.owncloud.android.files.services;
 
 import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashMap;
+import java.util.Map;
 
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
@@ -29,6 +29,7 @@ import com.owncloud.android.files.OwnCloudFileObserver;
 import com.owncloud.android.files.OwnCloudFileObserver.FileObserverStatusListener;
 import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
+import com.owncloud.android.operations.SynchronizeFileOperation;
 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
 import com.owncloud.android.utils.FileStorageUtils;
 
@@ -46,19 +47,18 @@ import android.util.Log;
 
 public class FileObserverService extends Service implements FileObserverStatusListener {
 
-    public final static String KEY_FILE_CMD = "KEY_FILE_CMD";
-    public final static String KEY_CMD_ARG_FILE = "KEY_CMD_ARG_FILE";
-    public final static String KEY_CMD_ARG_ACCOUNT = "KEY_CMD_ARG_ACCOUNT";
-
     public final static int CMD_INIT_OBSERVED_LIST = 1;
     public final static int CMD_ADD_OBSERVED_FILE = 2;
     public final static int CMD_DEL_OBSERVED_FILE = 3;
-    public final static int CMD_ADD_DOWNLOADING_FILE = 4;
+
+    public final static String KEY_FILE_CMD = "KEY_FILE_CMD";
+    public final static String KEY_CMD_ARG_FILE = "KEY_CMD_ARG_FILE";
+    public final static String KEY_CMD_ARG_ACCOUNT = "KEY_CMD_ARG_ACCOUNT";
 
     private static String TAG = FileObserverService.class.getSimpleName();
-    private static List<OwnCloudFileObserver> mObservers;
-    private static List<DownloadCompletedReceiver> mDownloadReceivers;
-    private static Object mReceiverListLock = new Object();
+
+    private static Map<String, OwnCloudFileObserver> mObserversMap;
+    private static DownloadCompletedReceiverBis mDownloadReceiver;
     private IBinder mBinder = new LocalBinder();
 
     public class LocalBinder extends Binder {
@@ -67,6 +67,28 @@ public class FileObserverService extends Service implements FileObserverStatusLi
         }
     }
     
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mDownloadReceiver = new DownloadCompletedReceiverBis();
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
+        filter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);        
+        registerReceiver(mDownloadReceiver, filter);
+        
+        mObserversMap = new HashMap<String, OwnCloudFileObserver>();
+        initializeObservedList();
+    }
+    
+    
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        unregisterReceiver(mDownloadReceiver);
+        mObserversMap = null;   // TODO study carefully the life cycle of Services to grant the best possible observance
+    }
+    
+    
     @Override
     public IBinder onBind(Intent intent) {
         return mBinder;
@@ -98,10 +120,6 @@ public class FileObserverService extends Service implements FileObserverStatusLi
                 removeObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE), 
                                     (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
                 break;
-            case CMD_ADD_DOWNLOADING_FILE:
-                addDownloadingFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
-                                    (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
-                break;
             default:
                 Log.wtf(TAG, "Incorrect key given");
         }
@@ -109,10 +127,13 @@ public class FileObserverService extends Service implements FileObserverStatusLi
         return Service.START_STICKY;
     }
 
+    
+    /**
+     * Read from the local database the list of files that must to be kept synchronized and 
+     * starts file observers to monitor local changes on them
+     */
     private void initializeObservedList() {
-        if (mObservers != null) return; // nothing to do here
-        mObservers = new ArrayList<OwnCloudFileObserver>();
-        mDownloadReceivers = new ArrayList<DownloadCompletedReceiver>();
+        mObserversMap.clear();
         Cursor c = getContentResolver().query(
                 ProviderTableMeta.CONTENT_URI,
                 null,
@@ -144,9 +165,11 @@ public class FileObserverService extends Service implements FileObserverStatusLi
             observer.setStorageManager(storage);
             observer.setOCFile(storage.getFileByPath(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))));
             observer.addObserverStatusListener(this);
-            observer.startWatching();
-            mObservers.add(observer);
-            Log.d(TAG, "Started watching file " + path);
+            mObserversMap.put(path, observer);
+            if (new File(path).exists()) {
+                observer.startWatching();
+                Log.d(TAG, "Started watching file " + path);
+            }
             
         } while (c.moveToNext());
         c.close();
@@ -155,33 +178,26 @@ public class FileObserverService extends Service implements FileObserverStatusLi
     /**
      * Registers the local copy of a remote file to be observed for local changes,
      * an automatically updated in the ownCloud server.
+     * 
+     * This method does NOT perform a {@link SynchronizeFileOperation} over the file. 
      *
+     * TODO We are ignoring that, currently, a local file can be linked to different files
+     * in ownCloud if it's uploaded several times. That's something pending to update: we 
+     * will avoid that the same local file is linked to different remote files.
+     * 
      * @param file      Object representing a remote file which local copy must be observed.
      * @param account   OwnCloud account containing file.
      */
     private void addObservedFile(OCFile file, Account account) {
         if (file == null) {
-            Log.e(TAG, "Trying to observe a NULL file");
+            Log.e(TAG, "Trying to add a NULL file to observer");
             return;
         }
-        if (mObservers == null) {
-            // this is very rare case when service was killed by system
-            // and observers list was deleted in that procedure
-            initializeObservedList();
-        }
         String localPath = file.getStoragePath();
-        if (!file.isDown()) {
-            // this is a file downloading / to be download for the first time
+        if (localPath == null || localPath.length() <= 0) { // file downloading / to be download for the first time
             localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
         }
-        OwnCloudFileObserver tmpObserver = null, observer = null;
-        for (int i = 0; i < mObservers.size(); ++i) {
-            tmpObserver = mObservers.get(i);
-            if (tmpObserver.getPath().equals(localPath)) {
-                observer = tmpObserver;
-            }
-            tmpObserver.setContext(getApplicationContext());   // 'refreshing' context to all the observers? why?
-        }
+        OwnCloudFileObserver observer = mObserversMap.get(localPath);
         if (observer == null) {
             /// the local file was never registered to observe before
             observer = new OwnCloudFileObserver(localPath, OwnCloudFileObserver.CHANGES_ONLY);
@@ -194,28 +210,14 @@ public class FileObserverService extends Service implements FileObserverStatusLi
             observer.setOCFile(file);
             observer.addObserverStatusListener(this);
             observer.setContext(getApplicationContext());
-            
-        } else {
-            /* LET'S IGNORE THAT, CURRENTLY, A LOCAL FILE CAN BE LINKED TO DIFFERENT FILES IN OWNCLOUD;
-             * we should change that
-             * 
-            /// the local file is already observed for some other OCFile(s)
-            observer.addOCFile(account, file);  // OCFiles should have a reference to the account containing them to not be confused
-            */ 
-        }
 
-        mObservers.add(observer);
-        Log.d(TAG, "Observer added for path " + localPath);
+            mObserversMap.put(localPath, observer);
+            Log.d(TAG, "Observer added for path " + localPath);
         
-        if (!file.isDown()) {
-            // if the file is not down, it can't be observed for changes
-            DownloadCompletedReceiver receiver = new DownloadCompletedReceiver(localPath, observer);
-            registerReceiver(receiver, new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE));
-
-        } else {
-            observer.startWatching();
-            Log.d(TAG, "Started watching " + localPath);
-            
+            if (file.isDown()) {
+                observer.startWatching();
+                Log.d(TAG, "Started watching " + localPath);
+            }   // else - the observance can't be started on a file not already down; mDownloadReceiver will get noticed when the download of the file finishes
         }
         
     }
@@ -224,76 +226,35 @@ public class FileObserverService extends Service implements FileObserverStatusLi
     /**
      * Unregisters the local copy of a remote file to be observed for local changes.
      *
+     * Starts to watch it, if the file has a local copy to watch.
+     * 
+     * TODO We are ignoring that, currently, a local file can be linked to different files
+     * in ownCloud if it's uploaded several times. That's something pending to update: we 
+     * will avoid that the same local file is linked to different remote files.
+     *
      * @param file      Object representing a remote file which local copy must be not observed longer.
      * @param account   OwnCloud account containing file.
      */
     private void removeObservedFile(OCFile file, Account account) {
         if (file == null) {
-            Log.e(TAG, "Trying to unobserve a NULL file");
+            Log.e(TAG, "Trying to remove a NULL file");
             return;
         }
-        if (mObservers == null) {
-            initializeObservedList();
-        }
         String localPath = file.getStoragePath();
-        if (!file.isDown()) {
-            // this happens when a file not in the device is set to be kept synchronized, and quickly unset again,
-            // while the download is not finished
+        if (localPath == null || localPath.length() <= 0) {
             localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
         }
         
-        for (int i = 0; i < mObservers.size(); ++i) {
-            OwnCloudFileObserver observer = mObservers.get(i);
-            if (observer.getPath().equals(localPath)) {
-                observer.stopWatching();
-                mObservers.remove(i);       // assuming, again, that a local file can be only linked to only ONE remote file; currently false
-                if (!file.isDown()) {
-                    // TODO unregister download receiver ;forget this until list of receivers is replaced for a single receiver
-                }
-                Log.d(TAG, "Stopped watching " + localPath);
-                break;
-            }
+        OwnCloudFileObserver observer = mObserversMap.get(localPath);
+        if (observer != null) {
+            observer.stopWatching();
+            mObserversMap.remove(observer);
+            Log.d(TAG, "Stopped watching " + localPath);
         }
         
     }
 
     
-    /**
-     * Temporarily disables the observance of a file that is going to be download.
-     *
-     * @param file      Object representing the remote file which local copy must not be observed temporarily.
-     * @param account   OwnCloud account containing file.
-     */
-    private void addDownloadingFile(OCFile file, Account account) {
-        OwnCloudFileObserver observer = null;
-        for (OwnCloudFileObserver o : mObservers) {
-            if (o.getRemotePath().equals(file.getRemotePath()) && o.getAccount().equals(account)) {
-                observer = o;
-                break;
-            }
-        }
-        if (observer == null) {
-            Log.e(TAG, "Couldn't find observer for remote file " + file.getRemotePath());
-            return;
-        }
-        observer.stopWatching();
-        DownloadCompletedReceiver dcr = new DownloadCompletedReceiver(observer.getPath(), observer);
-        registerReceiver(dcr, new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE));
-    }
-
-    
-    private static void addReceiverToList(DownloadCompletedReceiver r) {
-        synchronized(mReceiverListLock) {
-            mDownloadReceivers.add(r);
-        }
-    }
-    
-    private static void removeReceiverFromList(DownloadCompletedReceiver r) {
-        synchronized(mReceiverListLock) {
-            mDownloadReceivers.remove(r);
-        }
-    }
-
     @Override
     public void onObservedFileStatusUpdate(String localPath, String remotePath, Account account, RemoteOperationResult result) {
         if (!result.isSuccess()) {
@@ -311,37 +272,34 @@ public class FileObserverService extends Service implements FileObserverStatusLi
             }
         } // else, nothing else to do; now it's duty of FileUploader service 
     }
+    
+    
 
-    private class DownloadCompletedReceiver extends BroadcastReceiver {
-        String mPath;
-        OwnCloudFileObserver mObserver;
-        
-        public DownloadCompletedReceiver(String path, OwnCloudFileObserver observer) {
-            mPath = path;
-            mObserver = observer;
-            addReceiverToList(this);
-        }
+    /**
+     *  Private receiver listening to events broadcast by the FileDownloader service.
+     * 
+     *  Starts and stops the observance on registered files when they are being download,
+     *  in order to avoid to start unnecessary synchronizations. 
+     */
+    private class DownloadCompletedReceiverBis extends BroadcastReceiver {
         
         @Override
         public void onReceive(Context context, Intent intent) {
-            if (mPath.equals(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH))) {
-                if ((new File(mPath)).exists()) {   
-                    // the download could be successful, or not; in both cases, the file could be down, due to a former download or upload
-                    context.unregisterReceiver(this);
-                    removeReceiverFromList(this);
-                    mObserver.startWatching();
-                    Log.d(TAG, "Started watching " + mPath);
-                    return;
-                }   // else - keep waiting for a future retry of the download ; 
-                    // mObserver.startWatching() won't ever work if the file is not in the device when it's called 
+            String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH);
+            OwnCloudFileObserver observer = mObserversMap.get(downloadPath);
+            if (observer != null) {
+                if (intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE) &&
+                        new File(downloadPath).exists()) {  // the download could be successful, or not; in both cases, the file could be down, due to a former download or upload   
+                    observer.startWatching();
+                    Log.d(TAG, "Watching again " + downloadPath);
+                
+                } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
+                    observer.stopWatching();
+                    Log.d(TAG, "Disabling observance of " + downloadPath);
+                } 
             }
         }
         
-        @Override
-        public boolean equals(Object o) {
-            if (o instanceof DownloadCompletedReceiver)
-                return mPath.equals(((DownloadCompletedReceiver)o).mPath);
-            return super.equals(o);
-        }
     }
+    
 }

+ 32 - 24
src/com/owncloud/android/operations/SynchronizeFileOperation.java

@@ -42,6 +42,7 @@ public class SynchronizeFileOperation extends RemoteOperation {
     private String TAG = SynchronizeFileOperation.class.getSimpleName();
     //private String mRemotePath;
     private OCFile mLocalFile;
+    private OCFile mServerFile;
     private DataStorageManager mStorageManager;
     private Account mAccount;
     private boolean mSyncFileContents;
@@ -51,23 +52,24 @@ public class SynchronizeFileOperation extends RemoteOperation {
     private boolean mTransferWasRequested = false;
     
     public SynchronizeFileOperation(
-            OCFile localFile, 
-            DataStorageManager dataStorageManager, 
+            OCFile localFile,
+            OCFile serverFile,          // make this null to let the operation checks the server; added to reuse info from SynchronizeFolderOperation 
+            DataStorageManager storageManager, 
             Account account, 
             boolean syncFileContents,
-            boolean localChangeAlreadyKnown,
+            boolean localChangeAlreadyKnown, 
             Context context) {
         
-        //mRemotePath = remotePath;
         mLocalFile = localFile;
-        mStorageManager = dataStorageManager;
+        mServerFile = serverFile;
+        mStorageManager = storageManager;
         mAccount = account;
         mSyncFileContents = syncFileContents;
         mLocalChangeAlreadyKnown = localChangeAlreadyKnown;
         mContext = context;
     }
 
-    
+
     @Override
     protected RemoteOperationResult run(WebdavClient client) {
         
@@ -83,29 +85,38 @@ public class SynchronizeFileOperation extends RemoteOperation {
             } else {
                 /// local copy in the device -> need to think a bit more before do anything
                 
-                propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mLocalFile.getRemotePath()));
-                int status = client.executeMethod(propfind);
-                boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS;
-                if (isMultiStatus) {
-                    MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
-                    WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
+                if (mServerFile == null) {
+                    /// take the duty of check the server for the current state of the file there
+                    propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mLocalFile.getRemotePath()));
+                    int status = client.executeMethod(propfind);
+                    boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS;
+                    if (isMultiStatus) {
+                        MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
+                        WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
                                                client.getBaseUri().getPath());
-                    OCFile serverFile = fillOCFile(we);
+                        mServerFile = fillOCFile(we);
+                        
+                    } else {
+                        client.exhaustResponse(propfind.getResponseBodyAsStream());
+                        result = new RemoteOperationResult(false, status);
+                    }
+                }
+                
+                if (result == null) {   // true if the server was not checked, or nothing was wrong with the remote request
               
                     /// check changes in server and local file
                     boolean serverChanged = false;
-                    if (serverFile.getEtag() != null) {
-                        serverChanged = (!serverFile.getEtag().equals(mLocalFile.getEtag()));   // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
+                    if (mServerFile.getEtag() != null) {
+                        serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag()));   // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
                     } else {
                         // server without etags
-                        serverChanged = (serverFile.getModificationTimestamp() > mLocalFile.getModificationTimestamp());
+                        serverChanged = (mServerFile.getModificationTimestamp() > mLocalFile.getModificationTimestamp());
                     }
                     boolean localChanged = (mLocalChangeAlreadyKnown || mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
                         // TODO this will be always true after the app is upgraded to database version 3; will result in unnecessary uploads
               
                     /// decide action to perform depending upon changes
                     if (localChanged && serverChanged) {
-                        // conflict
                         result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
                   
                     } else if (localChanged) {
@@ -125,9 +136,9 @@ public class SynchronizeFileOperation extends RemoteOperation {
                             // the update of local data will be done later by the FileUploader service when the upload finishes
                         } else {
                             // TODO CHECK: is this really useful in some point in the code?
-                            serverFile.setKeepInSync(mLocalFile.keepInSync());
-                            serverFile.setParentId(mLocalFile.getParentId());
-                            mStorageManager.saveFile(serverFile);
+                            mServerFile.setKeepInSync(mLocalFile.keepInSync());
+                            mServerFile.setParentId(mLocalFile.getParentId());
+                            mStorageManager.saveFile(mServerFile);
                             
                         }
                         result = new RemoteOperationResult(ResultCode.OK);
@@ -137,10 +148,7 @@ public class SynchronizeFileOperation extends RemoteOperation {
                         result = new RemoteOperationResult(ResultCode.OK);
                     }
               
-                } else {
-                    client.exhaustResponse(propfind.getResponseBodyAsStream());
-                    result = new RemoteOperationResult(false, status);
-                }
+                } 
           
             }
             

+ 63 - 40
src/com/owncloud/android/operations/SynchronizeFolderOperation.java

@@ -27,13 +27,11 @@ import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
 
 import android.accounts.Account;
 import android.content.Context;
-import android.content.Intent;
 import android.util.Log;
 
 import com.owncloud.android.datamodel.DataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.files.services.FileDownloader;
-import com.owncloud.android.files.services.FileObserverService;
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
 import com.owncloud.android.utils.FileStorageUtils;
 
 import eu.alefzero.webdav.WebdavClient;
@@ -70,6 +68,10 @@ public class SynchronizeFolderOperation extends RemoteOperation {
     
     /** Files and folders contained in the synchronized folder */
     private List<OCFile> mChildren;
+
+    private int mConflictsFound;
+
+    private int mFailsInFavouritesFound;
     
     
     public SynchronizeFolderOperation(  String remotePath, 
@@ -87,6 +89,14 @@ public class SynchronizeFolderOperation extends RemoteOperation {
     }
     
     
+    public int getConflictsFound() {
+        return mConflictsFound;
+    }
+    
+    public int getFailsInFavouritesFound() {
+        return mFailsInFavouritesFound;
+    }
+    
     /**
      * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
      * 
@@ -100,6 +110,8 @@ public class SynchronizeFolderOperation extends RemoteOperation {
     @Override
     protected RemoteOperationResult run(WebdavClient client) {
         RemoteOperationResult result = null;
+        mFailsInFavouritesFound = 0;
+        mConflictsFound = 0;
         
         // code before in FileSyncAdapter.fetchData
         PropFindMethod query = null;
@@ -118,24 +130,34 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
                     WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
                     OCFile parent = fillOCFile(we);
-                    parent.setParentId(mParentId);
                     mStorageManager.saveFile(parent);
                     mParentId = parent.getFileId();
                 }
                 
                 // read contents in folder
                 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
+                List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
                 for (int i = 1; i < resp.getResponses().length; ++i) {
                     WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
                     OCFile file = fillOCFile(we);
-                    file.setParentId(mParentId);
                     OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
                     if (oldFile != null) {
-                        if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) {
-                            disableObservance(file);        // first disable observer so we won't get file upload right after download
-                            requestContentDownload(file);
-                        }
                         file.setKeepInSync(oldFile.keepInSync());
+                        file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
+                        if (file.keepInSync()) {
+                            //disableObservance(file);        // first disable observer so we won't get file upload right after download
+                            //                                // now, the FileDownloader service sends a broadcast before start a download; the FileObserverService is listening for it
+                            //requestFileSynchronization(file, oldFile, client);
+                            SynchronizeFileOperation operation = new SynchronizeFileOperation(  oldFile,        
+                                                                                                file, 
+                                                                                                mStorageManager,
+                                                                                                mAccount,       
+                                                                                                true, 
+                                                                                                false,          
+                                                                                                mContext
+                                                                                                );
+                            filesToSyncContents.add(operation);
+                        }
                     }
                 
                     updatedFiles.add(file);
@@ -143,8 +165,28 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                                 
                 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
                 mStorageManager.saveFiles(updatedFiles);
-
                 
+                // request for the synchronization of files AFTER saving last properties
+                SynchronizeFileOperation op = null;
+                RemoteOperationResult contentsResult = null;
+                for (int i=0; i < filesToSyncContents.size(); i++) {
+                    op = filesToSyncContents.get(i);
+                    contentsResult = op.execute(client);   // returns without waiting for upload or download finishes
+                    if (!contentsResult.isSuccess()) {
+                        if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
+                            mConflictsFound++;
+                        } else {
+                            mFailsInFavouritesFound++;
+                            if (contentsResult.getException() != null) {
+                                Log.d(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
+                            } else {
+                                Log.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
+                            }
+                        }
+                    }   // won't let these fails break the synchronization process
+                }
+
+                    
                 // removal of obsolete files
                 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
                 OCFile file;
@@ -165,7 +207,16 @@ public class SynchronizeFolderOperation extends RemoteOperation {
             }
             
             // prepare result object
-            result = new RemoteOperationResult(isMultiStatus(status), status);
+            if (isMultiStatus(status)) {
+                if (mConflictsFound > 0  || mFailsInFavouritesFound > 0) { 
+                    result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);   // should be different result, but will do the job
+                            
+                } else {
+                    result = new RemoteOperationResult(true, status);
+                }
+            } else {
+                result = new RemoteOperationResult(false, status);
+            }
             Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
             
             
@@ -200,37 +251,9 @@ public class SynchronizeFolderOperation extends RemoteOperation {
         file.setMimetype(we.contentType());
         file.setModificationTimestamp(we.modifiedTimesamp());
         file.setLastSyncDateForProperties(mCurrentSyncTime);
+        file.setParentId(mParentId);
         return file;
     }
     
-    
-    /**
-     * Request to stop the observance of local updates for a file.  
-     * 
-     * @param file      OCFile representing the remote file to stop to monitor for local updates
-     */
-    private void disableObservance(OCFile file) {
-        Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
-        Intent intent = new Intent(mContext, FileObserverService.class);
-        intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
-        intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, file);
-        intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
-        mContext.startService(intent);
-        
-    }
-
-
-    /** 
-     * Requests a download to the file download service
-     * 
-     * @param   file    OCFile representing the remote file to download
-     */
-    private void requestContentDownload(OCFile file) {
-        Intent intent = new Intent(mContext, FileDownloader.class);
-        intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
-        intent.putExtra(FileDownloader.EXTRA_FILE, file);
-        mContext.startService(intent);
-    }
-
 
 }

+ 1 - 1
src/com/owncloud/android/operations/UpdateOCVersionOperation.java

@@ -42,7 +42,7 @@ import eu.alefzero.webdav.WebdavClient;
  */
 public class UpdateOCVersionOperation extends RemoteOperation {
 
-    private static final String TAG = UploadFileOperation.class.getSimpleName();
+    private static final String TAG = UpdateOCVersionOperation.class.getSimpleName();
 
     private Account mAccount;
     private Context mContext;

+ 45 - 38
src/com/owncloud/android/syncadapter/FileSyncAdapter.java

@@ -28,15 +28,10 @@ import com.owncloud.android.R;
 import com.owncloud.android.datamodel.DataStorageManager;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
-//<<<<<<< HEAD
 import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.SynchronizeFolderOperation;
 import com.owncloud.android.operations.UpdateOCVersionOperation;
-/*=======
-import com.owncloud.android.files.services.FileDownloader;
-import com.owncloud.android.files.services.FileObserverService;
-import com.owncloud.android.utils.OwnCloudVersion;
->>>>>>> origin/master*/
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
 
 import android.accounts.Account;
 import android.app.Notification;
@@ -71,6 +66,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private int mFailedResultsCounter;    
     private RemoteOperationResult mLastFailedResult;
     private SyncResult mSyncResult;
+    private int mConflictsFound;
+    private int mFailsInFavouritesFound;
     
     public FileSyncAdapter(Context context, boolean autoInitialize) {
         super(context, autoInitialize);
@@ -88,6 +85,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
         mFailedResultsCounter = 0;
         mLastFailedResult = null;
+        mConflictsFound = 0;
+        mFailsInFavouritesFound = 0;
         mSyncResult = syncResult;
         mSyncResult.fullSyncRequested = false;
         mSyncResult.delayUntil = 60*60*24; // sync after 24h
@@ -128,13 +127,15 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                 
                 /// notify the user about the failure of MANUAL synchronization
                 notifyFailedSynchronization();
+                
+            } else if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
+                notifyFailsInFavourites();
             }
             sendStickyBroadcast(false, null, mLastFailedResult);        // message to signal the end to the UI
         }
         
     }
-    
-    
+
     
     /**
      * Called by system SyncManager when a synchronization is required to be cancelled.
@@ -188,12 +189,16 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
         sendStickyBroadcast(true, remotePath, null);
         
-        if (result.isSuccess()) {
+        if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
+            
+            if (result.getCode() == ResultCode.SYNC_CONFLICT) {
+                mConflictsFound += synchFolderOp.getConflictsFound();
+                mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
+            }
             // synchronize children folders 
             List<OCFile> children = synchFolderOp.getChildren();
             fetchChildren(children);    // beware of the 'hidden' recursion here!
             
-//<<<<<<< HEAD
         } else {
             if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
                 mSyncResult.stats.numAuthExceptions++;
@@ -203,33 +208,6 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                 
             } else if (result.getException() instanceof IOException) { 
                 mSyncResult.stats.numIoExceptions++;
-/*=======
-                // insertion or update of files
-                List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
-                for (int i = 1; i < resp.getResponses().length; ++i) {
-                    WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());
-                    OCFile file = fillOCFile(we);
-                    file.setParentId(parentId);
-                    if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&
-                            getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&
-                            file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())
-                                                                         .getModificationTimestamp()) {
-                        // first disable observer so we won't get file upload right after download
-                        Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
-                        Intent intent = new Intent(getContext(), FileObserverService.class);
-                        intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
-                        intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());
-                        getContext().startService(intent);
-                        intent = new Intent(this.getContext(), FileDownloader.class);
-                        intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
-                        intent.putExtra(FileDownloader.EXTRA_FILE, file);
-                        file.setKeepInSync(true);
-                        getContext().startService(intent);
-                    }
-                    if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
-                        file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
->>>>>>> origin/master*/
-                
             }
             mFailedResultsCounter++;
             mLastFailedResult = result;
@@ -308,6 +286,35 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
     }
 
-    
+
+    /**
+     * Notifies the user about conflicts and strange fails when trying to synchronize the contents of favourite files.
+     * 
+     * By now, we won't consider a failed synchronization.
+     */
+    private void notifyFailsInFavourites() {
+        if (mFailedResultsCounter > 0) {
+            Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
+            notification.flags |= Notification.FLAG_AUTO_CANCEL;
+            // TODO put something smart in the contentIntent below
+            notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
+            notification.setLatestEventInfo(getContext().getApplicationContext(), 
+                                            getContext().getString(R.string.sync_fail_in_favourites_ticker), 
+                                            String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound), 
+                                            notification.contentIntent);
+            ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
+            
+        } else {
+            Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
+            notification.flags |= Notification.FLAG_AUTO_CANCEL;
+            // TODO put something smart in the contentIntent below
+            notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
+            notification.setLatestEventInfo(getContext().getApplicationContext(), 
+                                            getContext().getString(R.string.sync_conflicts_in_favourites_ticker), 
+                                            String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound), 
+                                            notification.contentIntent);
+            ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
+        } 
+    }
 
 }

+ 1 - 1
src/com/owncloud/android/ui/fragment/FileDetailFragment.java

@@ -306,7 +306,7 @@ public class FileDetailFragment extends SherlockFragment implements
                     }
                     
                 } else {
-                    mLastRemoteOperation = new SynchronizeFileOperation(mFile, mStorageManager, mAccount, true, false, getActivity());
+                    mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
                     WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
                     mLastRemoteOperation.execute(wc, this, mHandler);