Fixed minor bugs inserted in clean-up
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
index 3763908..c3370f2 100644 (file)
@@ -1,9 +1,10 @@
 /* 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 3 of the License, or\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
 package com.owncloud.android.syncadapter;\r
 \r
 import java.io.IOException;\r
-import java.net.UnknownHostException;\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.authentication.AuthenticatorActivity;\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.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
@@ -65,6 +72,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     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
@@ -82,14 +93,24 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         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
-        \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 (UnknownHostException e) {\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
@@ -120,13 +141,20 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                 \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
     \r
     /**\r
      * Called by system SyncManager when a synchronization is required to be cancelled.\r
@@ -180,7 +208,15 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
         sendStickyBroadcast(true, remotePath, null);\r
         \r
-        if (result.isSuccess()) {\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
@@ -194,7 +230,6 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                 \r
             } else if (result.getException() instanceof IOException) { \r
                 mSyncResult.stats.numIoExceptions++;\r
-                \r
             }\r
             mFailedResultsCounter++;\r
             mLastFailedResult = result;\r
@@ -214,6 +249,7 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
             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
@@ -264,15 +300,95 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     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
-        // TODO put something smart in the contentIntent below\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
-        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
+        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