Merge pull request #1048 from owncloud/shareWithYou_icon_in_fileList
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
index f78ed24..43ddae3 100644 (file)
-/* ownCloud Android client application\r
- *   Copyright (C) 2011  Bartek Przybylski\r
- *   Copyright (C) 2012-2013 ownCloud Inc.\r
- *\r
- *   This program is free software: you can redistribute it and/or modify\r
- *   it under the terms of the GNU General Public License as published by\r
- *   the Free Software Foundation, either version 2 of the License, or\r
- *   (at your option) any later version.\r
- *\r
- *   This program is distributed in the hope that it will be useful,\r
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- *   GNU General Public License for more details.\r
- *\r
- *   You should have received a copy of the GNU General Public License\r
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.\r
- *\r
- */\r
-\r
-package com.owncloud.android.syncadapter;\r
-\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.apache.jackrabbit.webdav.DavException;\r
-\r
-import com.owncloud.android.R;\r
-import com.owncloud.android.datamodel.DataStorageManager;\r
-import com.owncloud.android.datamodel.FileDataStorageManager;\r
-import com.owncloud.android.datamodel.OCFile;\r
-import com.owncloud.android.operations.RemoteOperationResult;\r
-import com.owncloud.android.operations.SynchronizeFolderOperation;\r
-import com.owncloud.android.operations.UpdateOCVersionOperation;\r
-import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\r
-import com.owncloud.android.ui.activity.AuthenticatorActivity;\r
-import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;\r
-\r
-import android.accounts.Account;\r
-import android.accounts.AccountsException;\r
-import android.app.Notification;\r
-import android.app.NotificationManager;\r
-import android.app.PendingIntent;\r
-import android.content.ContentProviderClient;\r
-import android.content.ContentResolver;\r
-import android.content.Context;\r
-import android.content.Intent;\r
-import android.content.SyncResult;\r
-import android.os.Bundle;\r
-import android.util.Log;\r
-\r
-/**\r
- * SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
- * platform ContactOperations provider.\r
- * \r
- * @author Bartek Przybylski\r
- */\r
-public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {\r
-\r
-    private final static String TAG = "FileSyncAdapter";\r
-\r
-    /** \r
-     * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation\r
-     */\r
-    private static final int MAX_FAILED_RESULTS = 3; \r
-    \r
-    private long mCurrentSyncTime;\r
-    private boolean mCancellation;\r
-    private boolean mIsManualSync;\r
-    private int mFailedResultsCounter;    \r
-    private RemoteOperationResult mLastFailedResult;\r
-    private SyncResult mSyncResult;\r
-    private int mConflictsFound;\r
-    private int mFailsInFavouritesFound;\r
-    private Map<String, String> mForgottenLocalFiles;\r
-\r
-    \r
-    public FileSyncAdapter(Context context, boolean autoInitialize) {\r
-        super(context, autoInitialize);\r
-    }\r
-\r
-    /**\r
-     * {@inheritDoc}\r
-     */\r
-    @Override\r
-    public synchronized void onPerformSync(Account account, Bundle extras,\r
-            String authority, ContentProviderClient provider,\r
-            SyncResult syncResult) {\r
-\r
-        mCancellation = false;\r
-        mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
-        mFailedResultsCounter = 0;\r
-        mLastFailedResult = null;\r
-        mConflictsFound = 0;\r
-        mFailsInFavouritesFound = 0;\r
-        mForgottenLocalFiles = new HashMap<String, String>();\r
-        mSyncResult = syncResult;\r
-        mSyncResult.fullSyncRequested = false;\r
-        mSyncResult.delayUntil = 60*60*24; // sync after 24h\r
-\r
-        this.setAccount(account);\r
-        this.setContentProvider(provider);\r
-        this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));\r
-        try {\r
-            this.initClientForCurrentAccount();\r
-        } catch (IOException e) {\r
-            /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again\r
-            mSyncResult.tooManyRetries = true;\r
-            notifyFailedSynchronization();\r
-            return;\r
-        } catch (AccountsException e) {\r
-            /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again\r
-            mSyncResult.tooManyRetries = true;\r
-            notifyFailedSynchronization();\r
-            return;\r
-        }\r
-        \r
-        Log.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");\r
-        sendStickyBroadcast(true, null, null);  // message to signal the start of the synchronization to the UI\r
-        \r
-        try {\r
-            updateOCVersion();\r
-            mCurrentSyncTime = System.currentTimeMillis();\r
-            if (!mCancellation) {\r
-                fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);\r
-                \r
-            } else {\r
-                Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");\r
-            }\r
-            \r
-            \r
-        } finally {\r
-            // it's important making this although very unexpected errors occur; that's the reason for the finally\r
-            \r
-            if (mFailedResultsCounter > 0 && mIsManualSync) {\r
-                /// don't let the system synchronization manager retries MANUAL synchronizations\r
-                //      (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)\r
-                mSyncResult.tooManyRetries = true;\r
-                \r
-                /// notify the user about the failure of MANUAL synchronization\r
-                notifyFailedSynchronization();\r
-                \r
-            }\r
-            if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {\r
-                notifyFailsInFavourites();\r
-            }\r
-            if (mForgottenLocalFiles.size() > 0) {\r
-                notifyForgottenLocalFiles();\r
-                \r
-            }\r
-            sendStickyBroadcast(false, null, mLastFailedResult);        // message to signal the end to the UI\r
-        }\r
-        \r
-    }\r
-\r
-    \r
-    /**\r
-     * Called by system SyncManager when a synchronization is required to be cancelled.\r
-     * \r
-     * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder\r
-     * fetched will be still saved in the database. See onPerformSync implementation.\r
-     */\r
-    @Override\r
-    public void onSyncCanceled() {\r
-        Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");\r
-        mCancellation = true;\r
-        super.onSyncCanceled();\r
-    }\r
-    \r
-    \r
-    /**\r
-     * Updates the locally stored version value of the ownCloud server\r
-     */\r
-    private void updateOCVersion() {\r
-        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());\r
-        RemoteOperationResult result = update.execute(getClient());\r
-        if (!result.isSuccess()) {\r
-            mLastFailedResult = result; \r
-        }\r
-    }\r
-\r
-    \r
-    \r
-    /**\r
-     * Synchronize the properties of files and folders contained in a remote folder given by remotePath.\r
-     * \r
-     * @param remotePath        Remote path to the folder to synchronize.\r
-     * @param parentId          Database Id of the folder to synchronize.\r
-     */\r
-    private void fetchData(String remotePath, long parentId) {\r
-        \r
-        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))\r
-            return;\r
-        \r
-        // perform folder synchronization\r
-        SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, \r
-                                                                                    mCurrentSyncTime, \r
-                                                                                    parentId, \r
-                                                                                    getStorageManager(), \r
-                                                                                    getAccount(), \r
-                                                                                    getContext()\r
-                                                                                  );\r
-        RemoteOperationResult result = synchFolderOp.execute(getClient());\r
-        \r
-        \r
-        // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
-        sendStickyBroadcast(true, remotePath, null);\r
-        \r
-        if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {\r
-            \r
-            if (result.getCode() == ResultCode.SYNC_CONFLICT) {\r
-                mConflictsFound += synchFolderOp.getConflictsFound();\r
-                mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();\r
-            }\r
-            if (synchFolderOp.getForgottenLocalFiles().size() > 0) {\r
-                mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());\r
-            }\r
-            // synchronize children folders \r
-            List<OCFile> children = synchFolderOp.getChildren();\r
-            fetchChildren(children);    // beware of the 'hidden' recursion here!\r
-            \r
-        } else {\r
-            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
-                mSyncResult.stats.numAuthExceptions++;\r
-                \r
-            } else if (result.getException() instanceof DavException) {\r
-                mSyncResult.stats.numParseExceptions++;\r
-                \r
-            } else if (result.getException() instanceof IOException) { \r
-                mSyncResult.stats.numIoExceptions++;\r
-            }\r
-            mFailedResultsCounter++;\r
-            mLastFailedResult = result;\r
-        }\r
-            \r
-    }\r
-\r
-    /**\r
-     * Checks if a failed result should terminate the synchronization process immediately, according to\r
-     * OUR OWN POLICY\r
-     * \r
-     * @param   failedResult        Remote operation result to check.\r
-     * @return                      'True' if the result should immediately finish the synchronization\r
-     */\r
-    private boolean isFinisher(RemoteOperationResult failedResult) {\r
-        if  (failedResult != null) {\r
-            RemoteOperationResult.ResultCode code = failedResult.getCode();\r
-            return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||\r
-                    code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||\r
-                    code.equals(RemoteOperationResult.ResultCode.UNAUTHORIZED) ||\r
-                    code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||\r
-                    code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));\r
-        }\r
-        return false;\r
-    }\r
-\r
-    /**\r
-     * Synchronize data of folders in the list of received files\r
-     * \r
-     * @param files         Files to recursively fetch \r
-     */\r
-    private void fetchChildren(List<OCFile> files) {\r
-        int i;\r
-        for (i=0; i < files.size() && !mCancellation; i++) {\r
-            OCFile newFile = files.get(i);\r
-            if (newFile.isDirectory()) {\r
-                fetchData(newFile.getRemotePath(), newFile.getFileId());\r
-            }\r
-        }\r
-        if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");\r
-    }\r
-\r
-    \r
-    /**\r
-     * Sends a message to any application component interested in the progress of the synchronization.\r
-     * \r
-     * @param inProgress        'True' when the synchronization progress is not finished.\r
-     * @param dirRemotePath     Remote path of a folder that was just synchronized (with or without success)\r
-     */\r
-    private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {\r
-        Intent i = new Intent(FileSyncService.SYNC_MESSAGE);\r
-        i.putExtra(FileSyncService.IN_PROGRESS, inProgress);\r
-        i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);\r
-        if (dirRemotePath != null) {\r
-            i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);\r
-        }\r
-        if (result != null) {\r
-            i.putExtra(FileSyncService.SYNC_RESULT, result);\r
-        }\r
-        getContext().sendStickyBroadcast(i);\r
-    }\r
-\r
-    \r
-    \r
-    /**\r
-     * Notifies the user about a failed synchronization through the status notification bar \r
-     */\r
-    private void notifyFailedSynchronization() {\r
-        Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());\r
-        notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
-        boolean needsToUpdateCredentials = (mLastFailedResult != null && mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED);\r
-        // TODO put something smart in the contentIntent below for all the possible errors\r
-        notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
-        if (needsToUpdateCredentials) {\r
-            // let the user update credentials with one click\r
-            Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);\r
-            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());\r
-            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);\r
-            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
-            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);\r
-            updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);\r
-            notification.contentIntent = PendingIntent.getActivity(getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);\r
-            notification.setLatestEventInfo(getContext().getApplicationContext(), \r
-                    getContext().getString(R.string.sync_fail_ticker), \r
-                    String.format(getContext().getString(R.string.sync_fail_content_unauthorized), getAccount().name), \r
-                    notification.contentIntent);\r
-        } else {\r
-            notification.setLatestEventInfo(getContext().getApplicationContext(), \r
-                    getContext().getString(R.string.sync_fail_ticker), \r
-                    String.format(getContext().getString(R.string.sync_fail_content), getAccount().name), \r
-                    notification.contentIntent);\r
-        }\r
-        ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
-    }\r
-\r
-\r
-    /**\r
-     * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.\r
-     * \r
-     * By now, we won't consider a failed synchronization.\r
-     */\r
-    private void notifyFailsInFavourites() {\r
-        if (mFailedResultsCounter > 0) {\r
-            Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());\r
-            notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
-            // TODO put something smart in the contentIntent below\r
-            notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
-            notification.setLatestEventInfo(getContext().getApplicationContext(), \r
-                                            getContext().getString(R.string.sync_fail_in_favourites_ticker), \r
-                                            String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound), \r
-                                            notification.contentIntent);\r
-            ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);\r
-            \r
-        } else {\r
-            Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());\r
-            notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
-            // TODO put something smart in the contentIntent below\r
-            notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
-            notification.setLatestEventInfo(getContext().getApplicationContext(), \r
-                                            getContext().getString(R.string.sync_conflicts_in_favourites_ticker), \r
-                                            String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound), \r
-                                            notification.contentIntent);\r
-            ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);\r
-        } \r
-    }\r
-\r
-    \r
-    /**\r
-     * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because \r
-     * copying them inside the ownCloud local directory was not possible.\r
-     * \r
-     * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have \r
-     * synchronization problems if a local file is linked to more than one remote file.\r
-     * \r
-     * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.\r
-     */\r
-    private void notifyForgottenLocalFiles() {\r
-        Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());\r
-        notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
-\r
-        /// includes a pending intent in the notification showing a more detailed explanation\r
-        Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);\r
-        explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());\r
-        ArrayList<String> remotePaths = new ArrayList<String>();\r
-        ArrayList<String> localPaths = new ArrayList<String>();\r
-        remotePaths.addAll(mForgottenLocalFiles.keySet());\r
-        localPaths.addAll(mForgottenLocalFiles.values());\r
-        explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);\r
-        explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);  \r
-        explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\r
-        \r
-        notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);\r
-        notification.setLatestEventInfo(getContext().getApplicationContext(), \r
-                                        getContext().getString(R.string.sync_foreign_files_forgotten_ticker), \r
-                                        String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size(), getContext().getString(R.string.app_name)), \r
-                                        notification.contentIntent);\r
-        ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);\r
-        \r
-    }\r
-    \r
-    \r
-}\r
+/**
+ *   ownCloud Android client application
+ *
+ *   @author Bartek Przybylski
+ *   @author David A. Velasco
+ *   Copyright (C) 2011  Bartek Przybylski
+ *   Copyright (C) 2015 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.syncadapter;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.jackrabbit.webdav.DavException;
+
+import com.owncloud.android.MainApp;
+import com.owncloud.android.R;
+import com.owncloud.android.authentication.AuthenticatorActivity;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.lib.common.operations.RemoteOperationResult;
+import com.owncloud.android.operations.RefreshFolderOperation;
+import com.owncloud.android.operations.UpdateOCVersionOperation;
+import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
+import com.owncloud.android.lib.common.utils.Log_OC;
+import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
+
+import android.accounts.Account;
+import android.accounts.AccountsException;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.AbstractThreadedSyncAdapter;
+import android.content.ContentProviderClient;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SyncResult;
+import android.os.Bundle;
+import android.support.v4.app.NotificationCompat;
+
+/**
+ * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing 
+ * ownCloud files.
+ * 
+ * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle,
+ * String, ContentProviderClient, SyncResult)}.
+ */
+public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
+
+    private final static String TAG = FileSyncAdapter.class.getSimpleName();
+
+    /** Maximum number of failed folder synchronizations that are supported before finishing
+     * the synchronization operation */
+    private static final int MAX_FAILED_RESULTS = 3; 
+    
+    
+    public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() +
+            ".EVENT_FULL_SYNC_START";
+    public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() +
+            ".EVENT_FULL_SYNC_END";
+    public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED =
+            FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
+    //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED =
+    // FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
+    
+    public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() +
+            ".EXTRA_ACCOUNT_NAME";
+    public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() +
+            ".EXTRA_FOLDER_PATH";
+    public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT";
+    
+    
+    /** Time stamp for the current synchronization process, used to distinguish fresh data */
+    private long mCurrentSyncTime;
+    
+    /** Flag made 'true' when a request to cancel the synchronization is received */
+    private boolean mCancellation;
+    
+    /** When 'true' the process was requested by the user through the user interface;
+     *  when 'false', it was requested automatically by the system */
+    private boolean mIsManualSync;
+    
+    /** Counter for failed operations in the synchronization process */
+    private int mFailedResultsCounter;
+    
+    /** Result of the last failed operation */
+    private RemoteOperationResult mLastFailedResult;
+    
+    /** Counter of conflicts found between local and remote files */
+    private int mConflictsFound;
+    
+    /** Counter of failed operations in synchronization of kept-in-sync files */
+    private int mFailsInFavouritesFound;
+    
+    /** Map of remote and local paths to files that where locally stored in a location out
+     * of the ownCloud folder and couldn't be copied automatically into it */
+    private Map<String, String> mForgottenLocalFiles;
+
+    /** {@link SyncResult} instance to return to the system when the synchronization finish */
+    private SyncResult mSyncResult;
+
+    /** 'True' means that the server supports the share API */
+    private boolean mIsShareSupported;
+    
+    
+    /**
+     * Creates a {@link FileSyncAdapter}
+     *
+     * {@inheritDoc}
+     */
+    public FileSyncAdapter(Context context, boolean autoInitialize) {
+        super(context, autoInitialize);
+    }
+
+    
+    /**
+     * Creates a {@link FileSyncAdapter}
+     *
+     * {@inheritDoc}
+     */
+    public FileSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
+        super(context, autoInitialize, allowParallelSyncs);
+    }
+
+    
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public synchronized void onPerformSync(Account account, Bundle extras,
+            String authority, ContentProviderClient providerClient,
+            SyncResult syncResult) {
+
+        mCancellation = false;
+        mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
+        mFailedResultsCounter = 0;
+        mLastFailedResult = null;
+        mConflictsFound = 0;
+        mFailsInFavouritesFound = 0;
+        mForgottenLocalFiles = new HashMap<String, String>();
+        mSyncResult = syncResult;
+        mSyncResult.fullSyncRequested = false;
+        mSyncResult.delayUntil = 60*60*24; // avoid too many automatic synchronizations
+
+        this.setAccount(account);
+        this.setContentProviderClient(providerClient);
+        this.setStorageManager(new FileDataStorageManager(account, providerClient));
+        
+        try {
+            this.initClientForCurrentAccount();
+        } catch (IOException e) {
+            /// the account is unknown for the Synchronization Manager, unreachable this context,
+            // or can not be authenticated; don't try this again
+            mSyncResult.tooManyRetries = true;
+            notifyFailedSynchronization();
+            return;
+        } catch (AccountsException e) {
+            /// the account is unknown for the Synchronization Manager, unreachable this context,
+            // or can not be authenticated; don't try this again
+            mSyncResult.tooManyRetries = true;
+            notifyFailedSynchronization();
+            return;
+        }
+        
+        Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
+        sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null);  // message to signal the start
+                                                                // of the synchronization to the UI
+        
+        try {
+            updateOCVersion();
+            mCurrentSyncTime = System.currentTimeMillis();
+            if (!mCancellation) {
+                synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
+                
+            } else {
+                Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder " +
+                        "because cancelation request");
+            }
+            
+            
+        } finally {
+            // it's important making this although very unexpected errors occur;
+            // that's the reason for the finally
+            
+            if (mFailedResultsCounter > 0 && mIsManualSync) {
+                /// don't let the system synchronization manager retries MANUAL synchronizations
+                //      (be careful: "MANUAL" currently includes the synchronization requested when
+                //      a new account is created and when the user changes the current account)
+                mSyncResult.tooManyRetries = true;
+                
+                /// notify the user about the failure of MANUAL synchronization
+                notifyFailedSynchronization();
+            }
+            if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
+                notifyFailsInFavourites();
+            }
+            if (mForgottenLocalFiles.size() > 0) {
+                notifyForgottenLocalFiles();
+            }
+            sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult);   // message to signal
+                                                                                // the end to the UI
+        }
+        
+    }
+    
+    /**
+     * Called by system SyncManager when a synchronization is required to be cancelled.
+     * 
+     * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later, 
+     * before a new folder is fetched. Data of the last folder synchronized will be still 
+     * locally saved. 
+     * 
+     * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
+     * and {@link #synchronizeFolder(OCFile)}.
+     */
+    @Override
+    public void onSyncCanceled() {
+        Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
+        mCancellation = true;
+        super.onSyncCanceled();
+    }
+    
+    
+    /**
+     * Updates the locally stored version value of the ownCloud server
+     */
+    private void updateOCVersion() {
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
+        RemoteOperationResult result = update.execute(getClient());
+        if (!result.isSuccess()) {
+            mLastFailedResult = result; 
+        } else {
+            mIsShareSupported = update.getOCVersion().isSharedSupported();
+        }
+    }
+    
+    
+    /**
+     *  Synchronizes the list of files contained in a folder identified with its remote path.
+     *  
+     *  Fetches the list and properties of the files contained in the given folder, including their 
+     *  properties, and updates the local database with them.
+     *  
+     *  Enters in the child folders to synchronize their contents also, following a recursive
+     *  depth first strategy. 
+     * 
+     *  @param folder                   Folder to synchronize.
+     */
+    private void synchronizeFolder(OCFile folder) {
+        
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
+            return;
+        
+        /*
+        OCFile folder, 
+        long currentSyncTime, 
+        boolean updateFolderProperties,
+        boolean syncFullAccount,
+        DataStorageManager dataStorageManager, 
+        Account account, 
+        Context context ) {
+        }
+        */
+        // folder synchronization
+        RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder,
+                                                                                   mCurrentSyncTime,
+                                                                                   true,
+                                                                                   mIsShareSupported,
+                                                                                   false,
+                                                                                   getStorageManager(),
+                                                                                   getAccount(),
+                                                                                   getContext()
+                                                                                  );
+        RemoteOperationResult result = synchFolderOp.execute(getClient());
+        
+        
+        // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
+        sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED, folder.getRemotePath(), result);
+        
+        // check the result of synchronizing the folder
+        if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
+            
+            if (result.getCode() == ResultCode.SYNC_CONFLICT) {
+                mConflictsFound += synchFolderOp.getConflictsFound();
+                mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
+            }
+            if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
+                mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
+            }
+            if (result.isSuccess()) {
+                // synchronize children folders 
+                List<OCFile> children = synchFolderOp.getChildren();
+                // beware of the 'hidden' recursion here!
+                fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged());
+            }
+            
+        } else {
+            // in failures, the statistics for the global result are updated
+            if (    result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
+                    result.isIdPRedirection()
+                ) {
+                mSyncResult.stats.numAuthExceptions++;
+                
+            } else if (result.getException() instanceof DavException) {
+                mSyncResult.stats.numParseExceptions++;
+                
+            } else if (result.getException() instanceof IOException) { 
+                mSyncResult.stats.numIoExceptions++;
+            }
+            mFailedResultsCounter++;
+            mLastFailedResult = result;
+        }
+            
+    }
+
+    /**
+     * Checks if a failed result should terminate the synchronization process immediately,
+     * according to OUR OWN POLICY
+     * 
+     * @param   failedResult        Remote operation result to check.
+     * @return                      'True' if the result should immediately finish the
+     *                              synchronization
+     */
+    private boolean isFinisher(RemoteOperationResult failedResult) {
+        if  (failedResult != null) {
+            RemoteOperationResult.ResultCode code = failedResult.getCode();
+            return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
+                    code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
+                    code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
+                    code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
+        }
+        return false;
+    }
+
+    /**
+     * Triggers the synchronization of any folder contained in the list of received files.
+     * 
+     * @param files         Files to recursively synchronize.
+     */
+    private void fetchChildren(OCFile parent, List<OCFile> files, boolean parentEtagChanged) {
+        int i;
+        OCFile newFile = null;
+        //String etag = null;
+        //boolean syncDown = false;
+        for (i=0; i < files.size() && !mCancellation; i++) {
+            newFile = files.get(i);
+            if (newFile.isFolder()) {
+                /*
+                etag = newFile.getEtag();
+                syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
+                if(syncDown) { */
+                    synchronizeFolder(newFile);
+                    //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(),
+                    // null);
+                //}
+            }
+        }
+       
+        if (mCancellation && i <files.size()) Log_OC.d(TAG,
+                "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() +
+                        " due to cancelation request");
+    }
+
+    
+    /**
+     * Sends a message to any application component interested in the progress of the
+     * synchronization.
+     * 
+     * @param event             Event in the process of synchronization to be notified.   
+     * @param dirRemotePath     Remote path of the folder target of the event occurred.
+     * @param result            Result of an individual {@ SynchronizeFolderOperation},
+     *                          if completed; may be null.
+     */
+    private void sendLocalBroadcast(String event, String dirRemotePath,
+                                    RemoteOperationResult result) {
+        Log_OC.d(TAG, "Send broadcast " + event);
+        Intent intent = new Intent(event);
+        intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
+        if (dirRemotePath != null) {
+            intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
+        }
+        if (result != null) {
+            intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
+        }
+        getContext().sendStickyBroadcast(intent);
+        //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
+    }
+
+    
+    
+    /**
+     * Notifies the user about a failed synchronization through the status notification bar 
+     */
+    private void notifyFailedSynchronization() {
+        NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
+        boolean needsToUpdateCredentials = (
+                mLastFailedResult != null && (  
+                        mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
+                        mLastFailedResult.isIdPRedirection()
+                )
+        );
+        if (needsToUpdateCredentials) {
+            // let the user update credentials with one click
+            Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
+            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
+            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
+                    AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
+            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+            updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
+            notificationBuilder
+                .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
+                .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
+                .setContentIntent(PendingIntent.getActivity(
+                    getContext(), (int)System.currentTimeMillis(), updateAccountCredentials,
+                        PendingIntent.FLAG_ONE_SHOT
+                ))
+                .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
+        } else {
+            notificationBuilder
+                .setTicker(i18n(R.string.sync_fail_ticker))
+                .setContentTitle(i18n(R.string.sync_fail_ticker))
+                .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
+        }
+        
+        showNotification(R.string.sync_fail_ticker, notificationBuilder);
+    }
+
+
+    /**
+     * Notifies the user about conflicts and strange fails when trying to synchronize the contents
+     * of kept-in-sync files.
+     * 
+     * By now, we won't consider a failed synchronization.
+     */
+    private void notifyFailsInFavourites() {
+        if (mFailedResultsCounter > 0) {
+            NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
+            notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
+                
+            // TODO put something smart in the contentIntent below
+            notificationBuilder
+                .setContentIntent(PendingIntent.getActivity(
+                    getContext(), (int) System.currentTimeMillis(), new Intent(), 0
+                ))
+                .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
+                .setContentText(i18n(R.string.sync_fail_in_favourites_content,
+                        mFailedResultsCounter + mConflictsFound, mConflictsFound));
+            
+            showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
+        } else {
+            NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
+            notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
+          
+            // TODO put something smart in the contentIntent below
+            notificationBuilder
+                .setContentIntent(PendingIntent.getActivity(
+                    getContext(), (int) System.currentTimeMillis(), new Intent(), 0
+                ))
+                .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
+                .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
+            
+            showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
+        } 
+    }
+    
+    /**
+     * Notifies the user about local copies of files out of the ownCloud local directory that
+     * were 'forgotten' because copying them inside the ownCloud local directory was not possible.
+     * 
+     * We don't want links to files out of the ownCloud local directory (foreign files) anymore.
+     * It's easy to have synchronization problems if a local file is linked to more than one
+     * remote file.
+     * 
+     * We won't consider a synchronization as failed when foreign files can not be copied to
+     * the ownCloud local directory.
+     */
+    private void notifyForgottenLocalFiles() {
+        NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
+        notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
+      
+        /// includes a pending intent in the notification showing a more detailed explanation
+        Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
+        explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
+        ArrayList<String> remotePaths = new ArrayList<String>();
+        ArrayList<String> localPaths = new ArrayList<String>();
+        remotePaths.addAll(mForgottenLocalFiles.keySet());
+        localPaths.addAll(mForgottenLocalFiles.values());
+        explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
+        explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);  
+        explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        
+        notificationBuilder
+            .setContentIntent(PendingIntent.getActivity(
+                getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
+            ))
+            .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
+            .setContentText(i18n(R.string.sync_foreign_files_forgotten_content,
+                    mForgottenLocalFiles.size(), i18n(R.string.app_name)));
+        
+        showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
+    }
+    
+    /**
+     * Creates a notification builder with some commonly used settings
+     * 
+     * @return
+     */
+    private NotificationCompat.Builder createNotificationBuilder() {
+        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
+        notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
+        return notificationBuilder;
+    }
+    
+    /**
+     * Builds and shows the notification
+     * 
+     * @param id
+     * @param builder
+     */
+    private void showNotification(int id, NotificationCompat.Builder builder) {
+        ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE))
+            .notify(id, builder.build());
+    }
+    /**
+     * Shorthand translation
+     * 
+     * @param key
+     * @param args
+     * @return
+     */
+    private String i18n(int key, Object... args) {
+        return getContext().getString(key, args);
+    }
+}