Fixed local path NULL when making favourite a file not down ; fixed change of local...
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
index c5776de..ea833d4 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
+//<<<<<<< HEAD
 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.files.services.FileDownloader;\r
+import com.owncloud.android.files.services.FileObserverService;\r
 import com.owncloud.android.utils.OwnCloudVersion;\r
+>>>>>>> origin/master*/
 \r
 import android.accounts.Account;\r
 import android.app.Notification;\r
@@ -45,7 +49,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
@@ -55,17 +58,27 @@ import eu.alefzero.webdav.WebdavClient;
  */\r
 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {\r
 \r
-    private final static String TAG = "FileSyncAdapter"; \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 boolean mRightSync;\r
+    private int mFailedResultsCounter;    \r
+    private RemoteOperationResult mLastFailedResult;\r
+    private SyncResult mSyncResult;\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
@@ -73,39 +86,50 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
 \r
         mCancellation = false;\r
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
-        mRightSync = true;\r
-        \r
+        mFailedResultsCounter = 0;\r
+        mLastFailedResult = null;\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
-        sendStickyBroadcast(true, null);  // message to signal the start to the UI\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
-            mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0);\r
-            if (!mRightSync && mIsManualSync) {\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
-            sendStickyBroadcast(false, null);        // message to signal the end to the UI\r
+            sendStickyBroadcast(false, null, mLastFailedResult);        // message to signal the end to the UI\r
         }\r
         \r
     }\r
@@ -130,31 +154,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
@@ -165,19 +168,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
+    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
@@ -187,47 +182,90 @@ 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);\r
+        sendStickyBroadcast(true, remotePath, null);\r
         \r
         if (result.isSuccess()) {\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
+//<<<<<<< HEAD
         } 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
+                mSyncResult.stats.numIoExceptions++;\r
+/*=======
+                // insertion or update of files\r
+                List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);\r
+                for (int i = 1; i < resp.getResponses().length; ++i) {\r
+                    WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());\r
+                    OCFile file = fillOCFile(we);\r
+                    file.setParentId(parentId);\r
+                    if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&\r
+                            getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&\r
+                            file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())\r
+                                                                         .getModificationTimestamp()) {\r
+                        // first disable observer so we won't get file upload right after download\r
+                        Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());\r
+                        Intent intent = new Intent(getContext(), FileObserverService.class);\r
+                        intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);\r
+                        intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());\r
+                        getContext().startService(intent);\r
+                        intent = new Intent(this.getContext(), FileDownloader.class);\r
+                        intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());\r
+                        intent.putExtra(FileDownloader.EXTRA_FILE, file);\r
+                        file.setKeepInSync(true);\r
+                        getContext().startService(intent);\r
+                    }\r
+                    if (getStorageManager().getFileByPath(file.getRemotePath()) != null)\r
+                        file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());\r
+>>>>>>> origin/master*/
                 \r
-            } else if (result.getException() != null) {\r
-                // TODO maybe something smarter with syncResult\r
-                mRightSync = false;\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.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
-     * @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
@@ -235,21 +273,21 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
 \r
     \r
     /**\r
-     * Sends a message to any app component interested in the progress of the synchronization.\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
+    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
+        if (result != null) {\r
             i.putExtra(FileSyncService.SYNC_RESULT, result);\r
-        }*/\r
+        }\r
         getContext().sendStickyBroadcast(i);\r
     }\r
 \r