X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/blobdiff_plain/938c78466b89ee30d439462ded5b4b25c79190ce..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 7b803fc1..ea833d49 100644 --- a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java @@ -19,28 +19,36 @@ package com.owncloud.android.syncadapter; import java.io.IOException; +import java.net.UnknownHostException; import java.util.List; -import java.util.Vector; import org.apache.jackrabbit.webdav.DavException; -import org.apache.jackrabbit.webdav.MultiStatus; -import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; +import com.owncloud.android.R; +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.accounts.AuthenticatorException; -import android.accounts.OperationCanceledException; +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; import android.content.ContentProviderClient; +import android.content.ContentResolver; import android.content.Context; 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 @@ -50,253 +58,256 @@ 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 Account mAccount; + 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, SyncResult syncResult) { mCancellation = false; - mAccount = account; - - this.setAccount(mAccount); + mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); + 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(mAccount, - getContentProvider())); - - /* Commented code for ugly performance tests - mDelaysIndex = 0; - mDelaysCount = 0; - */ + 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, "Synchronization of ownCloud account " + account.name + " starting"); + sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI - Log.d(TAG, "syncing owncloud account " + mAccount.name); - - sendStickyBroadcast(true, null); // message to signal the start to the UI - - PropFindMethod query = null; try { + updateOCVersion(); mCurrentSyncTime = System.currentTimeMillis(); - query = new PropFindMethod(getUri().toString() + "/"); - getClient().executeMethod(query); - MultiStatus resp = null; - 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(getUri().toString(), syncResult, file.getFileId()); - } + if (!mCancellation) { + fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID); + + } else { + Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested"); } - } catch (OperationCanceledException e) { - e.printStackTrace(); - } catch (AuthenticatorException e) { - syncResult.stats.numAuthExceptions++; - e.printStackTrace(); - } catch (IOException e) { - syncResult.stats.numIoExceptions++; - e.printStackTrace(); - } catch (DavException e) { - syncResult.stats.numIoExceptions++; - e.printStackTrace(); - } catch (Throwable t) { - // TODO update syncResult - Log.e(TAG, "problem while synchronizing owncloud account " + account.name, t); - t.printStackTrace(); + } finally { - if (query != null) - query.releaseConnection(); // let the connection available for other methods - } - - /* Commented code for ugly performance tests - long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE; - for (int i=0; i 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) + mSyncResult.tooManyRetries = true; + + /// notify the user about the failure of MANUAL synchronization + notifyFailedSynchronization(); + } + sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI } - mean = sum / mDelaysCount; - Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min); - sum = 0; max = 0; min = Long.MAX_VALUE; - for (int i=0; i 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! - // 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()) +//<<<<<<< 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) { + 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()) { - Intent intent = new Intent(this.getContext(), FileDownloader.class); - intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount()); - intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath()); - intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath()); - intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength()); - file.setKeepInSync(true); - getContext().startService(intent); - } - if (getStorageManager().getFileByPath(file.getRemotePath()) != null) - file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync()); + // 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*/ - //Log.v(TAG, "adding file: " + file); - updatedFiles.add(file); - if (parentId == 0) - parentId = file.getFileId(); - } - /* 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 - Vector files = getStorageManager().getDirectoryContent( - getStorageManager().getFileById(parentId)); - OCFile file; - String currentSavePath = FileDownloader.getSavePath(mAccount.name); - for (int i=0; i < files.size(); ) { - file = files.get(i); - if (file.getLastSyncDate() != mCurrentSyncTime) { - Log.v(TAG, "removing file: " + file); - getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath))); - files.remove(i); - } else { - i++; - } } + mFailedResultsCounter++; + mLastFailedResult = result; + } - // synchronized folder -> notice to UI - sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath()); - - // recursive fetch - for (int 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 (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; - */ + } - } catch (OperationCanceledException e) { - e.printStackTrace(); - } catch (AuthenticatorException e) { - syncResult.stats.numAuthExceptions++; - e.printStackTrace(); - } catch (IOException e) { - syncResult.stats.numIoExceptions++; - e.printStackTrace(); - } catch (DavException e) { - syncResult.stats.numIoExceptions++; - e.printStackTrace(); - } catch (Throwable t) { - // TODO update syncResult - Log.e(TAG, "problem while synchronizing owncloud account " + mAccount.name, t); - t.printStackTrace(); - - } finally { - if (query != null) - query.releaseConnection(); // let the connection available for other methods + /** + * 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; } - 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; + /** + * Synchronize data of folders in the list of received files + * + * @param files Files to recursively fetch + */ + 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(), newFile.getFileId()); + } + } + if (mCancellation && i