X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/blobdiff_plain/6e469559c558d87d7e3cc81fc024b597e00be313..9aab2d26da38f26e7ff03a0b5db3bd01b51bce05:/src/com/owncloud/android/syncadapter/FileSyncAdapter.java diff --git a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java index c5776de1..ea833d49 100644 --- a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java @@ -19,20 +19,24 @@ 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; +//<<<<<<< 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; @@ -45,7 +49,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 @@ -55,17 +58,27 @@ import eu.alefzero.webdav.WebdavClient; */ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { - private final static String TAG = "FileSyncAdapter"; + 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, @@ -73,39 +86,50 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { mCancellation = false; mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); - mRightSync = true; - + mFailedResultsCounter = 0; + mLastFailedResult = null; + mSyncResult = syncResult; + mSyncResult.fullSyncRequested = false; + mSyncResult.delayUntil = 60*60*24; // sync after 24h + 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); - - 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 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 - mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0); - if (!mRightSync && mIsManualSync) { + 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(); } - sendStickyBroadcast(false, null); // message to signal the end to the UI + sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI } } @@ -130,31 +154,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; } } @@ -165,19 +168,11 @@ 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) { - // 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"); + if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult)) return; - } // perform folder synchronization SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath, @@ -187,47 +182,90 @@ 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 - sendStickyBroadcast(true, remotePath); + sendStickyBroadcast(true, remotePath, null); if (result.isSuccess()) { // synchronize children folders List children = synchFolderOp.getChildren(); - fetchChildren(children, syncResult); // beware of the 'hidden' recursion here! + fetchChildren(children); // beware of the 'hidden' recursion here! +//<<<<<<< HEAD } 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++; +/*======= + // insertion or update of files + List updatedFiles = new Vector(resp.getResponses().length - 1); + for (int i = 1; i < resp.getResponses().length; ++i) { + WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath()); + OCFile file = fillOCFile(we); + file.setParentId(parentId); + if (getStorageManager().getFileByPath(file.getRemotePath()) != null && + getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() && + file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath()) + .getModificationTimestamp()) { + // first disable observer so we won't get file upload right after download + Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath()); + Intent intent = new Intent(getContext(), FileObserverService.class); + intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE); + intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath()); + getContext().startService(intent); + intent = new Intent(this.getContext(), FileDownloader.class); + intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount()); + intent.putExtra(FileDownloader.EXTRA_FILE, file); + file.setKeepInSync(true); + getContext().startService(intent); + } + if (getStorageManager().getFileByPath(file.getRemotePath()) != null) + file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync()); +>>>>>>> origin/master*/ - } else if (result.getException() != null) { - // TODO maybe something smarter with syncResult - mRightSync = false; } + mFailedResultsCounter++; + mLastFailedResult = result; } } /** + * 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)); + } + 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(List files, SyncResult syncResult) { + private void fetchChildren(List 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