Эх сурвалжийг харах

Changed the synchronization process to limit the number and type of failures supported before stop

David A. Velasco 12 жил өмнө
parent
commit
d25af7eea5

+ 2 - 7
src/com/owncloud/android/network/OwnCloudClientUtils.java

@@ -38,8 +38,6 @@ import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
 import org.apache.http.conn.ssl.X509HostnameVerifier;
 
 import com.owncloud.android.AccountUtils;
-import com.owncloud.android.authenticator.AccountAuthenticator;
-import com.owncloud.android.utils.OwnCloudVersion;
 
 import eu.alefzero.webdav.WebdavClient;
 
@@ -79,11 +77,8 @@ public class OwnCloudClientUtils {
     public static WebdavClient createOwnCloudClient (Account account, Context context) {
         Log.d(TAG, "Creating WebdavClient associated to " + account.name);
        
-        String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
-        OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
-        String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
-        
-        WebdavClient client = createOwnCloudClient(Uri.parse(baseUrl + webDavPath), context);
+        Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(context, account));
+        WebdavClient client = createOwnCloudClient(uri, context);
         
         String username = account.name.substring(0, account.name.lastIndexOf('@'));
         String password = AccountManager.get(context).getPassword(account);

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

@@ -119,7 +119,7 @@ public class DownloadFileOperation extends RemoteOperation {
     protected RemoteOperationResult run(WebdavClient client) {
         RemoteOperationResult result = null;
         File newFile = null;
-        boolean moved = false;
+        boolean moved = true;
         
         /// download will be performed to a temporal file, then moved to the final location
         File tmpFile = new File(getTmpPath());

+ 5 - 2
src/com/owncloud/android/operations/RemoteOperationResult.java

@@ -206,11 +206,14 @@ public class RemoteOperationResult implements Serializable {
             } else if (mException instanceof UnknownHostException) {
                 return "Unknown host exception";
         
-            } else if (mException instanceof SSLException) {
-                if (mCode == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)
+            } else if (mException instanceof CertificateCombinedException) {
+                if (((CertificateCombinedException) mException).isRecoverable())
                     return "SSL recoverable exception";
                 else
                     return "SSL exception";
+                
+            } else if (mException instanceof SSLException) {
+                return "SSL exception";
 
             } else if (mException instanceof DavException) {
                 return "Unexpected WebDAV exception";

+ 109 - 0
src/com/owncloud/android/operations/UpdateOCVersionOperation.java

@@ -0,0 +1,109 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2011  Bartek Przybylski
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   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.operations;
+
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.content.Context;
+import android.util.Log;
+
+import com.owncloud.android.AccountUtils;
+import com.owncloud.android.authenticator.AccountAuthenticator;
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
+import com.owncloud.android.utils.OwnCloudVersion;
+
+import eu.alefzero.webdav.WebdavClient;
+
+/**
+ * Remote operation that checks the version of an ownCloud server and stores it locally
+ * 
+ * @author David A. Velasco
+ */
+public class UpdateOCVersionOperation extends RemoteOperation {
+
+    private static final String TAG = UploadFileOperation.class.getCanonicalName();
+
+    private Account mAccount;
+    private Context mContext;
+    
+    
+    public UpdateOCVersionOperation(Account account, Context context) {
+        mAccount = account;
+        mContext = context;
+    }
+    
+    
+    @Override
+    protected RemoteOperationResult run(WebdavClient client) {
+        AccountManager accountMngr = AccountManager.get(mContext); 
+        String statUrl = accountMngr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
+        statUrl += AccountUtils.STATUS_PATH;
+        RemoteOperationResult result = null;
+        GetMethod get = null;
+        try {
+            get = new GetMethod(statUrl);
+            int status = client.executeMethod(get);
+            if (status != HttpStatus.SC_OK) {
+                client.exhaustResponse(get.getResponseBodyAsStream());
+                result = new RemoteOperationResult(false, status);
+                
+            } else {
+                String response = get.getResponseBodyAsString();
+                if (response != null) {
+                    JSONObject json = new JSONObject(response);
+                    if (json != null && json.getString("version") != null) {
+                        OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));
+                        if (ocver.isVersionValid()) {
+                            accountMngr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, ocver.toString());
+                            Log.d(TAG, "Got new OC version " + ocver.toString());
+                            result = new RemoteOperationResult(ResultCode.OK);
+                            
+                        } else {
+                            Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));
+                            result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
+                        }
+                    }
+                }
+                if (result == null) {
+                    result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
+                }
+            }
+            Log.i(TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage());
+            
+        } catch (JSONException e) {
+            result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
+            Log.e(TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage(), e);
+                
+        } catch (Exception e) {
+            result = new RemoteOperationResult(e);
+            Log.e(TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage(), e);
+            
+        } finally {
+            if (get != null) 
+                get.releaseConnection();
+        }
+        return result;
+    }
+
+}

+ 7 - 13
src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java

@@ -39,7 +39,6 @@ import android.accounts.OperationCanceledException;
 import android.content.AbstractThreadedSyncAdapter;
 import android.content.ContentProviderClient;
 import android.content.Context;
-import android.net.Uri;
 import eu.alefzero.webdav.WebdavClient;
 
 /**
@@ -143,19 +142,14 @@ public abstract class AbstractOwnCloudSyncAdapter extends
         return null;
     }
 
-    protected Uri getUri() {
-        return Uri.parse(AccountUtils.constructFullURLForAccount(getContext(), getAccount()));
-    }
-
-    protected WebdavClient getClient() throws /*OperationCanceledException,
-            AuthenticatorException,*/ IOException {
-        if (mClient == null) {
-            if (AccountUtils.constructFullURLForAccount(getContext(), getAccount()) == null) {
-                throw new UnknownHostException();
-            }
-            mClient = OwnCloudClientUtils.createOwnCloudClient(account, getContext());
+    protected void initClientForCurrentAccount() throws UnknownHostException {
+        if (AccountUtils.constructFullURLForAccount(getContext(), account) == null) {
+            throw new UnknownHostException();
         }
-
+        mClient = OwnCloudClientUtils.createOwnCloudClient(account, getContext());
+    }
+    
+    protected WebdavClient getClient() {
         return mClient;
     }
 }

+ 32 - 55
src/com/owncloud/android/syncadapter/FileSyncAdapter.java

@@ -19,20 +19,18 @@
 package com.owncloud.android.syncadapter;
 
 import java.io.IOException;
+import java.net.UnknownHostException;
 import java.util.List;
 
 import org.apache.jackrabbit.webdav.DavException;
-import org.json.JSONObject;
 
-import com.owncloud.android.AccountUtils;
 import com.owncloud.android.R;
-import com.owncloud.android.authenticator.AccountAuthenticator;
 import com.owncloud.android.datamodel.DataStorageManager;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.operations.RemoteOperationResult;
 import com.owncloud.android.operations.SynchronizeFolderOperation;
-import com.owncloud.android.utils.OwnCloudVersion;
+import com.owncloud.android.operations.UpdateOCVersionOperation;
 
 import android.accounts.Account;
 import android.app.Notification;
@@ -45,7 +43,6 @@ import android.content.Intent;
 import android.content.SyncResult;
 import android.os.Bundle;
 import android.util.Log;
-import eu.alefzero.webdav.WebdavClient;
 
 /**
  * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
@@ -67,11 +64,15 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private boolean mIsManualSync;
     private int mFailedResultsCounter;    
     private RemoteOperationResult mLastFailedResult;
+    private SyncResult mSyncResult;
     
     public FileSyncAdapter(Context context, boolean autoInitialize) {
         super(context, autoInitialize);
     }
 
+    /**
+     * {@inheritDoc}
+     */
     @Override
     public synchronized void onPerformSync(Account account, Bundle extras,
             String authority, ContentProviderClient provider,
@@ -81,32 +82,41 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
         mFailedResultsCounter = 0;
         mLastFailedResult = null;
+        mSyncResult = syncResult;
         
         this.setAccount(account);
         this.setContentProvider(provider);
         this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
+        try {
+            this.initClientForCurrentAccount();
+        } catch (UnknownHostException e) {
+            /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
+            mSyncResult.tooManyRetries = true;
+            notifyFailedSynchronization();
+            return;
+        }
         
-        Log.d(TAG, "syncing owncloud account " + account.name);
-
+        Log.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
         sendStickyBroadcast(true, null, null);  // message to signal the start of the synchronization to the UI
         
         try {
             updateOCVersion();
             mCurrentSyncTime = System.currentTimeMillis();
             if (!mCancellation) {
-                fetchData(OCFile.PATH_SEPARATOR, syncResult, DataStorageManager.ROOT_PARENT_ID);
+                fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);
                 
             } else {
                 Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");
             }
             
+            
         } 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)
-                syncResult.tooManyRetries = true;
+                mSyncResult.tooManyRetries = true;
                 
                 /// notify the user about the failure of MANUAL synchronization
                 notifyFailedSynchronization();
@@ -136,31 +146,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Updates the locally stored version value of the ownCloud server
      */
     private void updateOCVersion() {
-        String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);
-        statUrl += AccountUtils.STATUS_PATH;
-        
-        try {
-            String result = getClient().getResultAsString(statUrl);
-            if (result != null) {
-                try {
-                    JSONObject json = new JSONObject(result);
-                    if (json != null && json.getString("version") != null) {
-                        OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));
-                        if (ocver.isVersionValid()) {
-                            getAccountManager().setUserData(getAccount(), AccountAuthenticator.KEY_OC_VERSION, ocver.toString());
-                            Log.d(TAG, "Got new OC version " + ocver.toString());
-                        } else {
-                            Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));
-                        }
-                    }
-                } catch (Throwable e) {
-                    Log.w(TAG, "Couldn't parse version response", e);
-                }
-            } else {
-                Log.w(TAG, "Problem while getting ocversion from server");
-            }
-        } catch (Exception e) {
-            Log.e(TAG, "Problem getting response from server", e);
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
+        RemoteOperationResult result = update.execute(getClient());
+        if (!result.isSuccess()) {
+            mLastFailedResult = result; 
         }
     }
 
@@ -171,23 +160,12 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * 
      * @param remotePath        Remote path to the folder to synchronize.
      * @param parentId          Database Id of the folder to synchronize.
-     * @param syncResult        Object to update for communicate results to the system's synchronization manager.        
      */
-    private void fetchData(String remotePath, SyncResult syncResult, long parentId) {
+    private void fetchData(String remotePath, long parentId) {
         
-        if (mFailedResultsCounter > MAX_FAILED_RESULTS && isFinisher(mLastFailedResult))
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
             return;
         
-        // get client object to connect to the remote ownCloud server
-        WebdavClient client = null;
-        try {
-            client = getClient();
-        } catch (IOException e) {
-            syncResult.stats.numIoExceptions++;
-            Log.d(TAG, "Could not get client object while trying to synchronize - impossible to continue");
-            return;
-        }
-        
         // perform folder synchronization
         SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, 
                                                                                     mCurrentSyncTime, 
@@ -196,7 +174,7 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                                                                                     getAccount(), 
                                                                                     getContext()
                                                                                   );
-        RemoteOperationResult result = synchFolderOp.execute(client);
+        RemoteOperationResult result = synchFolderOp.execute(getClient());
         
         
         // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
@@ -205,17 +183,17 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         if (result.isSuccess()) {
             // synchronize children folders 
             List<OCFile> children = synchFolderOp.getChildren();
-            fetchChildren(children, syncResult);    // beware of the 'hidden' recursion here!
+            fetchChildren(children);    // beware of the 'hidden' recursion here!
             
         } else {
             if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
-                syncResult.stats.numAuthExceptions++;
+                mSyncResult.stats.numAuthExceptions++;
                 
             } else if (result.getException() instanceof DavException) {
-                syncResult.stats.numParseExceptions++;
+                mSyncResult.stats.numParseExceptions++;
                 
             } else if (result.getException() instanceof IOException) { 
-                syncResult.stats.numIoExceptions++;
+                mSyncResult.stats.numIoExceptions++;
                 
             }
             mFailedResultsCounter++;
@@ -246,14 +224,13 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Synchronize data of folders in the list of received files
      * 
      * @param files         Files to recursively fetch 
-     * @param syncResult    Updated object to provide results to the Synchronization Manager
      */
-    private void fetchChildren(List<OCFile> files, SyncResult syncResult) {
+    private void fetchChildren(List<OCFile> files) {
         int i;
         for (i=0; i < files.size() && !mCancellation; i++) {
             OCFile newFile = files.get(i);
             if (newFile.isDirectory()) {
-                fetchData(newFile.getRemotePath(), syncResult, newFile.getFileId());
+                fetchData(newFile.getRemotePath(), newFile.getFileId());
             }
         }
         if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");

+ 0 - 15
src/eu/alefzero/webdav/WebdavClient.java

@@ -337,19 +337,4 @@ public class WebdavClient extends HttpClient {
         return mUri;
     }
 
-    public String getResultAsString(String targetUrl) {
-        String getResult = null;
-        try {
-            GetMethod get = new GetMethod(targetUrl);
-            int status = executeMethod(get);
-            if (status == HttpStatus.SC_OK) {
-                getResult = get.getResponseBodyAsString();
-            }
-        } catch (Exception e) {
-            Log.e(TAG, "Error while getting requested file: " + targetUrl, e);
-            getResult = null;
-        }
-        return getResult;
-    }
-    
 }