Workaround to show hidden accents in options menu
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
index 1f0d908..e977e41 100644 (file)
 package com.owncloud.android.syncadapter;\r
 \r
 import java.io.IOException;\r
+import java.net.UnknownHostException;\r
 import java.util.List;\r
 \r
 import org.apache.jackrabbit.webdav.DavException;\r
-import org.json.JSONObject;\r
 \r
-import com.owncloud.android.AccountUtils;\r
 import com.owncloud.android.R;\r
-import com.owncloud.android.authenticator.AccountAuthenticator;\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.utils.OwnCloudVersion;\r
+import com.owncloud.android.operations.UpdateOCVersionOperation;\r
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\r
 \r
 import android.accounts.Account;\r
 import android.app.Notification;\r
@@ -45,7 +44,6 @@ import android.content.Intent;
 import android.content.SyncResult;\r
 import android.os.Bundle;\r
 import android.util.Log;\r
-import eu.alefzero.webdav.WebdavClient;\r
 \r
 /**\r
  * SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
@@ -67,11 +65,17 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private boolean mIsManualSync;\r
     private int mFailedResultsCounter;    \r
     private RemoteOperationResult mLastFailedResult;\r
+    private SyncResult mSyncResult;\r
+    private int mConflictsFound;\r
+    private int mFailsInFavouritesFound;\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
@@ -81,42 +85,57 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
         mFailedResultsCounter = 0;\r
         mLastFailedResult = null;\r
-        \r
+        mConflictsFound = 0;\r
+        mFailsInFavouritesFound = 0;\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 (UnknownHostException 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, "syncing owncloud account " + account.name);\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, syncResult, DataStorageManager.ROOT_PARENT_ID);\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
-                syncResult.tooManyRetries = true;\r
+                mSyncResult.tooManyRetries = true;\r
                 \r
                 /// notify the user about the failure of MANUAL synchronization\r
                 notifyFailedSynchronization();\r
+                \r
+            } else if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {\r
+                notifyFailsInFavourites();\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
@@ -136,31 +155,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Updates the locally stored version value of the ownCloud server\r
      */\r
     private void updateOCVersion() {\r
-        String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);\r
-        statUrl += AccountUtils.STATUS_PATH;\r
-        \r
-        try {\r
-            String result = getClient().getResultAsString(statUrl);\r
-            if (result != null) {\r
-                try {\r
-                    JSONObject json = new JSONObject(result);\r
-                    if (json != null && json.getString("version") != null) {\r
-                        OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));\r
-                        if (ocver.isVersionValid()) {\r
-                            getAccountManager().setUserData(getAccount(), AccountAuthenticator.KEY_OC_VERSION, ocver.toString());\r
-                            Log.d(TAG, "Got new OC version " + ocver.toString());\r
-                        } else {\r
-                            Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));\r
-                        }\r
-                    }\r
-                } catch (Throwable e) {\r
-                    Log.w(TAG, "Couldn't parse version response", e);\r
-                }\r
-            } else {\r
-                Log.w(TAG, "Problem while getting ocversion from server");\r
-            }\r
-        } catch (Exception e) {\r
-            Log.e(TAG, "Problem getting response from server", e);\r
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());\r
+        RemoteOperationResult result = update.execute(getClient());\r
+        if (!result.isSuccess()) {\r
+            mLastFailedResult = result; \r
         }\r
     }\r
 \r
@@ -171,22 +169,11 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * \r
      * @param remotePath        Remote path to the folder to synchronize.\r
      * @param parentId          Database Id of the folder to synchronize.\r
-     * @param syncResult        Object to update for communicate results to the system's synchronization manager.        \r
      */\r
-    private void fetchData(String remotePath, SyncResult syncResult, long parentId) {\r
-        \r
-        if (mFailedResultsCounter > MAX_FAILED_RESULTS && isFinisher(mLastFailedResult))\r
-            return;\r
+    private void fetchData(String remotePath, long parentId) {\r
         \r
-        // get client object to connect to the remote ownCloud server\r
-        WebdavClient client = null;\r
-        try {\r
-            client = getClient();\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            Log.d(TAG, "Could not get client object while trying to synchronize - impossible to continue");\r
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))\r
             return;\r
-        }\r
         \r
         // perform folder synchronization\r
         SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, \r
@@ -196,27 +183,31 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                                                                                     getAccount(), \r
                                                                                     getContext()\r
                                                                                   );\r
-        RemoteOperationResult result = synchFolderOp.execute(client);\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()) {\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
             // synchronize children folders \r
             List<OCFile> children = synchFolderOp.getChildren();\r
-            fetchChildren(children, syncResult);    // beware of the 'hidden' recursion here!\r
+            fetchChildren(children);    // beware of the 'hidden' recursion here!\r
             \r
         } else {\r
             if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
-                syncResult.stats.numAuthExceptions++;\r
+                mSyncResult.stats.numAuthExceptions++;\r
                 \r
             } else if (result.getException() instanceof DavException) {\r
-                syncResult.stats.numParseExceptions++;\r
+                mSyncResult.stats.numParseExceptions++;\r
                 \r
             } else if (result.getException() instanceof IOException) { \r
-                syncResult.stats.numIoExceptions++;\r
-                \r
+                mSyncResult.stats.numIoExceptions++;\r
             }\r
             mFailedResultsCounter++;\r
             mLastFailedResult = result;\r
@@ -246,14 +237,13 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Synchronize data of folders in the list of received files\r
      * \r
      * @param files         Files to recursively fetch \r
-     * @param syncResult    Updated object to provide results to the Synchronization Manager\r
      */\r
-    private void fetchChildren(List<OCFile> files, SyncResult syncResult) {\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(), syncResult, newFile.getFileId());\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
@@ -296,6 +286,35 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
     }\r
 \r
-    \r
+\r
+    /**\r
+     * Notifies the user about conflicts and strange fails when trying to synchronize the contents of favourite 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