From: David A. Velasco Date: Thu, 25 Oct 2012 08:41:24 +0000 (+0200) Subject: Merge two-way synch changes with synch-service refactoring for SSL warning X-Git-Tag: oc-android-1.4.3~132 X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/commitdiff_plain/d5a327c342b97ad4a7234fdbb533682f171c8716?hp=4ee94ba0f17d60fd0bc7470cea9c26e27d71f803 Merge two-way synch changes with synch-service refactoring for SSL warning --- diff --git a/src/com/owncloud/android/datamodel/DataStorageManager.java b/src/com/owncloud/android/datamodel/DataStorageManager.java index e824bdea..49a3cd73 100644 --- a/src/com/owncloud/android/datamodel/DataStorageManager.java +++ b/src/com/owncloud/android/datamodel/DataStorageManager.java @@ -23,6 +23,8 @@ import java.util.Vector; public interface DataStorageManager { + public static final int ROOT_PARENT_ID = 0; + public OCFile getFileByPath(String path); public OCFile getFileById(long id); diff --git a/src/com/owncloud/android/network/CertificateCombinedException.java b/src/com/owncloud/android/network/CertificateCombinedException.java index fad7a6f2..27427dd4 100644 --- a/src/com/owncloud/android/network/CertificateCombinedException.java +++ b/src/com/owncloud/android/network/CertificateCombinedException.java @@ -45,7 +45,7 @@ import javax.net.ssl.SSLPeerUnverifiedException; */ public class CertificateCombinedException extends RuntimeException { - /** Generated */ + /** Generated - to refresh every time the class changes */ private static final long serialVersionUID = -8875782030758554999L; private X509Certificate mServerCert = null; diff --git a/src/com/owncloud/android/network/OwnCloudClientUtils.java b/src/com/owncloud/android/network/OwnCloudClientUtils.java index 9cbc3fdc..5cc7a9fb 100644 --- a/src/com/owncloud/android/network/OwnCloudClientUtils.java +++ b/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); diff --git a/src/com/owncloud/android/operations/DownloadFileOperation.java b/src/com/owncloud/android/operations/DownloadFileOperation.java index e6120d69..c732c8b7 100644 --- a/src/com/owncloud/android/operations/DownloadFileOperation.java +++ b/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()); diff --git a/src/com/owncloud/android/operations/RemoteOperationResult.java b/src/com/owncloud/android/operations/RemoteOperationResult.java index 0618b86d..60b2b1a1 100644 --- a/src/com/owncloud/android/operations/RemoteOperationResult.java +++ b/src/com/owncloud/android/operations/RemoteOperationResult.java @@ -19,6 +19,7 @@ package com.owncloud.android.operations; import java.io.IOException; +import java.io.Serializable; import java.net.MalformedURLException; import java.net.SocketException; import java.net.SocketTimeoutException; @@ -29,6 +30,7 @@ import javax.net.ssl.SSLException; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; +import org.apache.jackrabbit.webdav.DavException; import com.owncloud.android.network.CertificateCombinedException; @@ -40,13 +42,18 @@ import com.owncloud.android.network.CertificateCombinedException; * * @author David A. Velasco */ -public class RemoteOperationResult { +public class RemoteOperationResult implements Serializable { + + /** Generated - to refresh every time the class changes */ + private static final long serialVersionUID = -7805531062432602444L; + public enum ResultCode { OK, OK_SSL, OK_NO_SSL, UNHANDLED_HTTP_CODE, + UNAUTHORIZED, FILE_NOT_FOUND, INSTANCE_NOT_CONFIGURED, UNKNOWN_ERROR, @@ -81,6 +88,9 @@ public class RemoteOperationResult { } else if (httpCode > 0) { switch (httpCode) { + case HttpStatus.SC_UNAUTHORIZED: + mCode = ResultCode.UNAUTHORIZED; + break; case HttpStatus.SC_NOT_FOUND: mCode = ResultCode.FILE_NOT_FOUND; break; @@ -196,11 +206,17 @@ public class RemoteOperationResult { } 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"; } else if (mException instanceof HttpException) { return "HTTP violation"; @@ -227,7 +243,7 @@ public class RemoteOperationResult { } return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess()?"success":"fail") + ")"; - + } } diff --git a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java new file mode 100644 index 00000000..91de06ec --- /dev/null +++ b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java @@ -0,0 +1,234 @@ +/* ownCloud Android client application + * Copyright (C) 2012 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 . + * + */ + +package com.owncloud.android.operations; + +import java.util.List; +import java.util.Vector; + +import org.apache.http.HttpStatus; +import org.apache.jackrabbit.webdav.MultiStatus; +import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; + +import android.accounts.Account; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import com.owncloud.android.datamodel.DataStorageManager; +import com.owncloud.android.datamodel.OCFile; +import com.owncloud.android.files.services.FileDownloader; +import com.owncloud.android.files.services.FileObserverService; + +import eu.alefzero.webdav.WebdavClient; +import eu.alefzero.webdav.WebdavEntry; +import eu.alefzero.webdav.WebdavUtils; + + +/** + * Remote operation performing the synchronization a the contents of a remote folder with the local database + * + * @author David A. Velasco + */ +public class SynchronizeFolderOperation extends RemoteOperation { + + private static final String TAG = SynchronizeFolderOperation.class.getCanonicalName(); + + /** Remote folder to synchronize */ + private String mRemotePath; + + /** Timestamp for the synchronization in progress */ + private long mCurrentSyncTime; + + /** Id of the folder to synchronize in the local database */ + private long mParentId; + + /** Access to the local database */ + private DataStorageManager mStorageManager; + + /** Account where the file to synchronize belongs */ + private Account mAccount; + + /** Android context; necessary to send requests to the download service; maybe something to refactor */ + private Context mContext; + + /** Files and folders contained in the synchronized folder */ + private List mChildren; + + + public SynchronizeFolderOperation( String remotePath, + long currentSyncTime, + long parentId, + DataStorageManager dataStorageManager, + Account account, + Context context ) { + mRemotePath = remotePath; + mCurrentSyncTime = currentSyncTime; + mParentId = parentId; + mStorageManager = dataStorageManager; + mAccount = account; + mContext = context; + } + + + /** + * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete. + * + * @return List of files and folders contained in the synchronized folder. + */ + public List getChildren() { + return mChildren; + } + + + @Override + protected RemoteOperationResult run(WebdavClient client) { + RemoteOperationResult result = null; + + // code before in FileSyncAdapter.fetchData + PropFindMethod query = null; + try { + Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath); + + // remote request + query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); + int status = client.executeMethod(query); + + // check and process response - /// TODO take into account all the possible status per child-resource + if (isMultiStatus(status)) { + MultiStatus resp = query.getResponseBodyAsMultiStatus(); + + // synchronize properties of the parent folder, if necessary + if (mParentId == DataStorageManager.ROOT_PARENT_ID) { + WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath()); + OCFile parent = fillOCFile(we); + parent.setParentId(mParentId); + mStorageManager.saveFile(parent); + mParentId = parent.getFileId(); + } + + // read contents in folder + List updatedFiles = new Vector(resp.getResponses().length - 1); + for (int i = 1; i < resp.getResponses().length; ++i) { + WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath()); + OCFile file = fillOCFile(we); + file.setParentId(mParentId); + OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath()); + if (oldFile != null) { + if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) { + disableObservance(file); // first disable observer so we won't get file upload right after download + requestContentDownload(file); + } + file.setKeepInSync(oldFile.keepInSync()); + } + + updatedFiles.add(file); + } + + // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed) + mStorageManager.saveFiles(updatedFiles); + + + // removal of obsolete files + mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId)); + OCFile file; + String currentSavePath = FileDownloader.getSavePath(mAccount.name); + for (int i=0; i < mChildren.size(); ) { + file = mChildren.get(i); + if (file.getLastSyncDate() != mCurrentSyncTime) { + Log.d(TAG, "removing file: " + file); + mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath))); + mChildren.remove(i); + } else { + i++; + } + } + + } else { + client.exhaustResponse(query.getResponseBodyAsStream()); + } + + // prepare result object + result = new RemoteOperationResult(isMultiStatus(status), status); + Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage()); + + + } catch (Exception e) { + result = new RemoteOperationResult(e); + Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException()); + + } finally { + if (query != null) + query.releaseConnection(); // let the connection available for other methods + } + + return result; + } + + + public boolean isMultiStatus(int status) { + return (status == HttpStatus.SC_MULTI_STATUS); + } + + + /** + * Creates and populates a new {@link OCFile} object with the data read from the server. + * + * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder). + * @return New OCFile instance representing the remote resource described by we. + */ + private OCFile fillOCFile(WebdavEntry we) { + OCFile file = new OCFile(we.decodedPath()); + file.setCreationTimestamp(we.createTimestamp()); + file.setFileLength(we.contentLength()); + file.setMimetype(we.contentType()); + file.setModificationTimestamp(we.modifiedTimesamp()); + file.setLastSyncDate(mCurrentSyncTime); + return file; + } + + + /** + * Request to stop the observance of local updates for a file. + * + * @param file OCFile representing the remote file to stop to monitor for local updates + */ + private void disableObservance(OCFile file) { + Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath()); + Intent intent = new Intent(mContext, FileObserverService.class); + intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE); + intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath()); + mContext.startService(intent); + + } + + + /** + * Requests a download to the file download service + * + * @param file OCFile representing the remote file to download + */ + private void requestContentDownload(OCFile file) { + Intent intent = new Intent(mContext, FileDownloader.class); + intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount); + intent.putExtra(FileDownloader.EXTRA_FILE, file); + mContext.startService(intent); + } + + +} diff --git a/src/com/owncloud/android/operations/UpdateOCVersionOperation.java b/src/com/owncloud/android/operations/UpdateOCVersionOperation.java new file mode 100644 index 00000000..dbe5df89 --- /dev/null +++ b/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 . + * + */ + +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; + } + +} diff --git a/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java b/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java index 878c6961..92c0b720 100644 --- a/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java +++ b/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; } } \ No newline at end of file diff --git a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java index 8c9a1535..b78b127b 100644 --- a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java @@ -19,23 +19,24 @@ package com.owncloud.android.syncadapter; import java.io.IOException; +import java.net.UnknownHostException; import java.util.List; -import java.util.Vector; -import org.apache.http.HttpStatus; import org.apache.jackrabbit.webdav.DavException; -import org.apache.jackrabbit.webdav.MultiStatus; -import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; -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; +//<<<<<<< HEAD +import com.owncloud.android.operations.RemoteOperationResult; +import com.owncloud.android.operations.SynchronizeFolderOperation; +import com.owncloud.android.operations.UpdateOCVersionOperation; +/*======= import com.owncloud.android.files.services.FileDownloader; import com.owncloud.android.files.services.FileObserverService; import com.owncloud.android.utils.OwnCloudVersion; +>>>>>>> origin/master*/ import android.accounts.Account; import android.app.Notification; @@ -48,8 +49,6 @@ import android.content.Intent; import android.content.SyncResult; import android.os.Bundle; import android.util.Log; -import eu.alefzero.webdav.WebdavEntry; -import eu.alefzero.webdav.WebdavUtils; /** * SyncAdapter implementation for syncing sample SyncAdapter contacts to the @@ -59,25 +58,27 @@ import eu.alefzero.webdav.WebdavUtils; */ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { - private final static String TAG = "FileSyncAdapter"; - - /* Commented code for ugly performance tests - private final static int MAX_DELAYS = 100; - private static long[] mResponseDelays = new long[MAX_DELAYS]; - private static long[] mSaveDelays = new long[MAX_DELAYS]; - private int mDelaysIndex = 0; - private int mDelaysCount = 0; - */ + private final static String TAG = "FileSyncAdapter"; + + /** + * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation + */ + private static final int MAX_FAILED_RESULTS = 3; private long mCurrentSyncTime; private boolean mCancellation; private boolean mIsManualSync; - private boolean mRightSync; + 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, @@ -85,123 +86,122 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { mCancellation = false; mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); - mRightSync = true; + 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; + } - /* Commented code for ugly performance tests - mDelaysIndex = 0; - mDelaysCount = 0; - */ - - Log.d(TAG, "syncing owncloud account " + account.name); - - sendStickyBroadcast(true, null); // message to signal the start to the UI + 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 - updateOCVersion(); - - String uri = getUri().toString(); - PropFindMethod query = null; try { + updateOCVersion(); mCurrentSyncTime = System.currentTimeMillis(); - query = new PropFindMethod(uri + "/"); - int status = getClient().executeMethod(query); - if (status != HttpStatus.SC_UNAUTHORIZED) { - MultiStatus resp = query.getResponseBodyAsMultiStatus(); - - if (resp.getResponses().length > 0) { - WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath()); - OCFile file = fillOCFile(we); - file.setParentId(0); - getStorageManager().saveFile(file); - if (!mCancellation) { - fetchData(uri, syncResult, file.getFileId()); - } - } - + if (!mCancellation) { + fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID); + } else { - syncResult.stats.numAuthExceptions++; + Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested"); } - } catch (IOException e) { - syncResult.stats.numIoExceptions++; - logException(e, uri + "/"); - - } catch (DavException e) { - syncResult.stats.numParseExceptions++; - logException(e, uri + "/"); - } catch (Exception e) { - // TODO something smart with syncresult - logException(e, uri + "/"); - mRightSync = false; } finally { - if (query != null) - query.releaseConnection(); // let the connection available for other methods - mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0); - if (!mRightSync && mIsManualSync) { + // 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 - Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis()); - notification.flags |= Notification.FLAG_AUTO_CANCEL; - // TODO put something smart in the contentIntent below - notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0); - notification.setLatestEventInfo(getContext().getApplicationContext(), - getContext().getString(R.string.sync_fail_ticker), - String.format(getContext().getString(R.string.sync_fail_content), account.name), - notification.contentIntent); - ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification); + notifyFailedSynchronization(); } - sendStickyBroadcast(false, null); // message to signal the end to the UI + sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI } - /* Commented code for ugly performance tests - long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE; - for (int i=0; i children = null; - try { - Log.d(TAG, "fetching " + uri); - - // remote request - query = new PropFindMethod(uri); - /* Commented code for ugly performance tests - long responseDelay = System.currentTimeMillis(); - */ - int status = getClient().executeMethod(query); - /* Commented code for ugly performance tests - responseDelay = System.currentTimeMillis() - responseDelay; - Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms"); - */ - if (status != HttpStatus.SC_UNAUTHORIZED) { - MultiStatus resp = query.getResponseBodyAsMultiStatus(); + + + /** + * Synchronize the properties of files and folders contained in a remote folder given by remotePath. + * + * @param remotePath Remote path to the folder to synchronize. + * @param parentId Database Id of the folder to synchronize. + */ + private void fetchData(String remotePath, long parentId) { + + if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult)) + return; + + // perform folder synchronization + SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath, + mCurrentSyncTime, + parentId, + getStorageManager(), + getAccount(), + getContext() + ); + RemoteOperationResult result = synchFolderOp.execute(getClient()); + + + // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess + sendStickyBroadcast(true, remotePath, null); + + if (result.isSuccess()) { + // synchronize children folders + List children = synchFolderOp.getChildren(); + fetchChildren(children); // beware of the 'hidden' recursion here! +//<<<<<<< HEAD + } else { + if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) { + mSyncResult.stats.numAuthExceptions++; + + } else if (result.getException() instanceof DavException) { + mSyncResult.stats.numParseExceptions++; + + } else if (result.getException() instanceof IOException) { + mSyncResult.stats.numIoExceptions++; +/*======= // insertion or update of files List updatedFiles = new Vector(resp.getResponses().length - 1); for (int i = 1; i < resp.getResponses().length; ++i) { @@ -226,170 +226,86 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { } if (getStorageManager().getFileByPath(file.getRemotePath()) != null) file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync()); +>>>>>>> origin/master*/ - // Log.v(TAG, "adding file: " + file); - updatedFiles.add(file); - } - /* Commented code for ugly performance tests - long saveDelay = System.currentTimeMillis(); - */ - getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update - /* Commented code for ugly performance tests - saveDelay = System.currentTimeMillis() - saveDelay; - Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms"); - */ - - // removal of obsolete files - children = getStorageManager().getDirectoryContent( - getStorageManager().getFileById(parentId)); - OCFile file; - String currentSavePath = FileDownloader.getSavePath(getAccount().name); - for (int i=0; i < children.size(); ) { - file = children.get(i); - if (file.getLastSyncDate() != mCurrentSyncTime) { - Log.v(TAG, "removing file: " + file); - getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath))); - children.remove(i); - } else { - i++; - } - } - - } else { - syncResult.stats.numAuthExceptions++; } - } catch (IOException e) { - syncResult.stats.numIoExceptions++; - logException(e, uri); - - } catch (DavException e) { - syncResult.stats.numParseExceptions++; - logException(e, uri); + mFailedResultsCounter++; + mLastFailedResult = result; + } - } catch (Exception e) { - // TODO something smart with syncresult - mRightSync = false; - logException(e, uri); - - } finally { - if (query != null) - query.releaseConnection(); // let the connection available for other methods + } - // synchronized folder -> notice to UI - sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath()); + /** + * 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)); } - - - fetchChildren(children, syncResult); - if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request"); - - - /* Commented code for ugly performance tests - mResponseDelays[mDelaysIndex] = responseDelay; - mSaveDelays[mDelaysIndex] = saveDelay; - mDelaysCount++; - mDelaysIndex++; - if (mDelaysIndex >= MAX_DELAYS) - mDelaysIndex = 0; - */ - + return false; } /** * 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(Vector files, SyncResult syncResult) { - for (int i=0; i < files.size() && !mCancellation; i++) { + private void fetchChildren(List files) { + int i; + for (i=0; i < files.size() && !mCancellation; i++) { OCFile newFile = files.get(i); - if (newFile.getMimetype().equals("DIR")) { - fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId()); + if (newFile.isDirectory()) { + fetchData(newFile.getRemotePath(), newFile.getFileId()); } } + if (mCancellation && i mDirectories; private OCFile mCurrentDir = null; @@ -100,6 +103,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements private FileDownloaderBinder mDownloaderBinder = null; private FileUploaderBinder mUploaderBinder = null; private ServiceConnection mDownloadConnection = null, mUploadConnection = null; + private RemoteOperationResult mLastSslUntrustedServerResult = null; private OCFileListFragment mFileList; @@ -110,6 +114,9 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements private static final int DIALOG_ABOUT_APP = 2; public static final int DIALOG_SHORT_WAIT = 3; private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4; + private static final int DIALOG_SSL_VALIDATOR = 5; + private static final int DIALOG_CERT_NOT_SAVED = 6; + private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1; private static final int ACTION_SELECT_MULTIPLE_FILES = 2; @@ -275,12 +282,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements break; } case R.id.startSync: { - ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account - Bundle bundle = new Bundle(); - bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); - ContentResolver.requestSync( - AccountUtils.getCurrentOwnCloudAccount(this), - AccountAuthenticator.AUTH_TOKEN_TYPE, bundle); + startSynchronization(); break; } case R.id.action_upload: { @@ -308,6 +310,16 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements return retval; } + private void startSynchronization() { + ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account + Bundle bundle = new Bundle(); + bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); + ContentResolver.requestSync( + AccountUtils.getCurrentOwnCloudAccount(this), + AccountAuthenticator.AUTH_TOKEN_TYPE, bundle); + } + + @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { int i = itemPosition; @@ -521,6 +533,15 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements Log.d(getClass().toString(), "onPause() end"); } + + @Override + protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { + if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) { + ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult); + } + } + + @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; @@ -646,6 +667,23 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements dialog = builder.create(); break; } + case DIALOG_SSL_VALIDATOR: { + dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this); + break; + } + case DIALOG_CERT_NOT_SAVED: { + builder = new AlertDialog.Builder(this); + builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved)); + builder.setCancelable(false); + builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + }; + }); + dialog = builder.create(); + break; + } default: dialog = null; } @@ -773,6 +811,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements } private class SyncBroadcastReceiver extends BroadcastReceiver { + /** * {@link BroadcastReceiver} to enable syncing feedback in UI */ @@ -810,6 +849,14 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements setSupportProgressBarIndeterminateVisibility(inProgress); } + + RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT); + if (synchResult != null) { + if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) { + mLastSslUntrustedServerResult = synchResult; + showDialog(DIALOG_SSL_VALIDATOR); + } + } } } @@ -1010,4 +1057,16 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements } + @Override + public void onSavedCertificate() { + startSynchronization(); + } + + + @Override + public void onFailedSavingCertificate() { + showDialog(DIALOG_CERT_NOT_SAVED); + } + + } diff --git a/src/eu/alefzero/webdav/WebdavClient.java b/src/eu/alefzero/webdav/WebdavClient.java index 6f98f500..61f16605 100644 --- a/src/eu/alefzero/webdav/WebdavClient.java +++ b/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; - } - }