package com.owncloud.android.operations;
-import java.io.IOException;
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 android.accounts.Account;
+import android.content.Context;
import android.content.Intent;
import android.util.Log;
-import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.DataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.services.FileDownloader;
private long mParentId;
/** Access to the local database */
- private FileDataStorageManager mStorageManager;
+ 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;
- SynchronizeFolderOperation(String remotePath, long currentSyncTime, long parentId, FileDataStorageManager storageManager, Account account) {
+ /** Files and folders contained in the synchronized folder */
+ private List<OCFile> mChildren;
+
+
+ public SynchronizeFolderOperation( String remotePath,
+ long currentSyncTime,
+ long parentId,
+ DataStorageManager dataStorageManager,
+ Account account,
+ Context context ) {
mRemotePath = remotePath;
mCurrentSyncTime = currentSyncTime;
mParentId = parentId;
- mStorageManager = storageManager;
+ 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<OCFile> getChildren() {
+ return mChildren;
}
// code before in FileSyncAdapter.fetchData
PropFindMethod query = null;
- Vector<OCFile> children = null;
try {
- Log.d(TAG, "Fetching files in " + mRemotePath);
+ 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
+ // check and process response - /// TODO take into account all the possible status per child-resource
if (isMultiStatus(status)) {
- /// TODO take into account all the possible status per child-resource
-
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<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
for (int i = 1; i < resp.getResponses().length; ++i) {
// removal of obsolete files
- children = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
+ mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
OCFile file;
String currentSavePath = FileDownloader.getSavePath(mAccount.name);
- for (int i=0; i < children.size(); ) {
- file = children.get(i);
+ 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)));
- children.remove(i);
+ mChildren.remove(i);
} else {
i++;
}
// prepare result object
result = new RemoteOperationResult(isMultiStatus(status), status);
- Log.i(TAG, "Synchronization of " + mRemotePath + ": " + result.getLogMessage());
+ Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
} catch (Exception e) {
- // TODO - distinguish IOException and DavException in RemoteOperationResult constructor
result = new RemoteOperationResult(e);
- Log.e(TAG, "Synchronization of " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+ Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
} finally {
if (query != null)
/**
- * Probably this code would be better in other place
+ * 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(this.getContext(), FileDownloader.class);
+ Intent intent = new Intent(mContext, FileDownloader.class);
intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
intent.putExtra(FileDownloader.EXTRA_FILE, file);
- getContext().startService(intent);
+ mContext.startService(intent);
}
\r
import java.io.IOException;\r
import java.util.List;\r
-import java.util.Vector;\r
\r
-import org.apache.http.HttpStatus;\r
import org.apache.jackrabbit.webdav.DavException;\r
-import org.apache.jackrabbit.webdav.MultiStatus;\r
-import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;\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
-import com.owncloud.android.files.services.FileDownloader;\r
import com.owncloud.android.operations.RemoteOperationResult;\r
+import com.owncloud.android.operations.SynchronizeFolderOperation;\r
import com.owncloud.android.utils.OwnCloudVersion;\r
\r
import android.accounts.Account;\r
import android.content.SyncResult;\r
import android.os.Bundle;\r
import android.util.Log;\r
-import eu.alefzero.webdav.WebdavEntry;\r
-import eu.alefzero.webdav.WebdavUtils;\r
+import eu.alefzero.webdav.WebdavClient;\r
\r
/**\r
* SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
\r
private final static String TAG = "FileSyncAdapter"; \r
\r
- /* Commented code for ugly performance tests\r
- private final static int MAX_DELAYS = 100;\r
- private static long[] mResponseDelays = new long[MAX_DELAYS]; \r
- private static long[] mSaveDelays = new long[MAX_DELAYS];\r
- private int mDelaysIndex = 0;\r
- private int mDelaysCount = 0;\r
- */\r
- \r
private long mCurrentSyncTime;\r
private boolean mCancellation;\r
private boolean mIsManualSync;\r
this.setContentProvider(provider);\r
this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));\r
\r
- /* Commented code for ugly performance tests\r
- mDelaysIndex = 0;\r
- mDelaysCount = 0;\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
\r
- updateOCVersion();\r
-\r
- String uri = getUri().toString();\r
- PropFindMethod query = null;\r
try {\r
+ updateOCVersion();\r
mCurrentSyncTime = System.currentTimeMillis();\r
- query = new PropFindMethod(uri + "/");\r
- int status = getClient().executeMethod(query);\r
- if (status != HttpStatus.SC_UNAUTHORIZED) {\r
- MultiStatus resp = query.getResponseBodyAsMultiStatus();\r
-\r
- if (resp.getResponses().length > 0) {\r
- WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath());\r
- OCFile file = fillOCFile(we);\r
- file.setParentId(0);\r
- getStorageManager().saveFile(file);\r
- if (!mCancellation) {\r
- fetchData(uri, syncResult, file.getFileId());\r
- }\r
- }\r
-\r
+ if (!mCancellation) {\r
+ fetchData(OCFile.PATH_SEPARATOR, syncResult, DataStorageManager.ROOT_PARENT_ID);\r
+ \r
} else {\r
- syncResult.stats.numAuthExceptions++;\r
+ Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");\r
}\r
- } catch (IOException e) {\r
- syncResult.stats.numIoExceptions++;\r
- logException(e, uri + "/");\r
- \r
- } catch (DavException e) {\r
- syncResult.stats.numParseExceptions++;\r
- logException(e, uri + "/");\r
- \r
- } catch (Exception e) {\r
- // TODO something smart with syncresult\r
- logException(e, uri + "/");\r
- mRightSync = false;\r
\r
} finally {\r
- if (query != null)\r
- query.releaseConnection(); // let the connection available for other methods\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
/// don't let the system synchronization manager retries MANUAL synchronizations\r
syncResult.tooManyRetries = true;\r
\r
/// notify the user about the failure of MANUAL synchronization\r
- Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());\r
- notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
- // TODO put something smart in the contentIntent below\r
- notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
- notification.setLatestEventInfo(getContext().getApplicationContext(), \r
- getContext().getString(R.string.sync_fail_ticker), \r
- String.format(getContext().getString(R.string.sync_fail_content), account.name), \r
- notification.contentIntent);\r
- ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
+ notifyFailedSynchronization();\r
}\r
sendStickyBroadcast(false, null); // message to signal the end to the UI\r
}\r
\r
- /* Commented code for ugly performance tests\r
- long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;\r
- for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {\r
- sum += mResponseDelays[i];\r
- max = Math.max(max, mResponseDelays[i]);\r
- min = Math.min(min, mResponseDelays[i]);\r
- }\r
- mean = sum / mDelaysCount;\r
- Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);\r
- \r
- sum = 0; max = 0; min = Long.MAX_VALUE;\r
- for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {\r
- sum += mSaveDelays[i];\r
- max = Math.max(max, mSaveDelays[i]);\r
- min = Math.min(min, mSaveDelays[i]);\r
- }\r
- mean = sum / mDelaysCount;\r
- Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);\r
- Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);\r
- */\r
- \r
}\r
-\r
- private void fetchData(String uri, SyncResult syncResult, long parentId) {\r
- PropFindMethod query = null;\r
- Vector<OCFile> children = null;\r
- try {\r
- Log.d(TAG, "fetching " + uri);\r
- \r
- // remote request \r
- query = new PropFindMethod(uri);\r
- /* Commented code for ugly performance tests\r
- long responseDelay = System.currentTimeMillis();\r
- */\r
- int status = getClient().executeMethod(query);\r
- /* Commented code for ugly performance tests\r
- responseDelay = System.currentTimeMillis() - responseDelay;\r
- Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");\r
- */\r
- if (status != HttpStatus.SC_UNAUTHORIZED) {\r
- MultiStatus resp = query.getResponseBodyAsMultiStatus();\r
- \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
- Intent 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
- \r
- // Log.v(TAG, "adding file: " + file);\r
- updatedFiles.add(file);\r
- }\r
- /* Commented code for ugly performance tests\r
- long saveDelay = System.currentTimeMillis();\r
- */ \r
- getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update\r
- /* Commented code for ugly performance tests\r
- saveDelay = System.currentTimeMillis() - saveDelay;\r
- Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");\r
- */\r
- \r
- // removal of obsolete files\r
- children = getStorageManager().getDirectoryContent(\r
- getStorageManager().getFileById(parentId));\r
- OCFile file;\r
- String currentSavePath = FileDownloader.getSavePath(getAccount().name);\r
- for (int i=0; i < children.size(); ) {\r
- file = children.get(i);\r
- if (file.getLastSyncDate() != mCurrentSyncTime) {\r
- Log.v(TAG, "removing file: " + file);\r
- getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));\r
- children.remove(i);\r
- } else {\r
- i++;\r
- }\r
- }\r
- \r
- } else {\r
- syncResult.stats.numAuthExceptions++;\r
- }\r
- } catch (IOException e) {\r
- syncResult.stats.numIoExceptions++;\r
- logException(e, uri);\r
- \r
- } catch (DavException e) {\r
- syncResult.stats.numParseExceptions++;\r
- logException(e, uri);\r
- \r
- } catch (Exception e) {\r
- // TODO something smart with syncresult\r
- mRightSync = false;\r
- logException(e, uri);\r
-\r
- } finally {\r
- if (query != null)\r
- query.releaseConnection(); // let the connection available for other methods\r
-\r
- // synchronized folder -> notice to UI\r
- sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());\r
- }\r
- \r
- \r
- fetchChildren(children, syncResult);\r
- if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");\r
- \r
- \r
- /* Commented code for ugly performance tests\r
- mResponseDelays[mDelaysIndex] = responseDelay;\r
- mSaveDelays[mDelaysIndex] = saveDelay;\r
- mDelaysCount++;\r
- mDelaysIndex++;\r
- if (mDelaysIndex >= MAX_DELAYS)\r
- mDelaysIndex = 0;\r
- */\r
- \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(Vector<OCFile> files, SyncResult syncResult) {\r
- for (int i=0; i < files.size() && !mCancellation; i++) {\r
- OCFile newFile = files.get(i);\r
- if (newFile.getMimetype().equals("DIR")) {\r
- fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId());\r
- }\r
- }\r
- }\r
-\r
\r
- private OCFile fillOCFile(WebdavEntry we) {\r
- OCFile file = new OCFile(we.decodedPath());\r
- file.setCreationTimestamp(we.createTimestamp());\r
- file.setFileLength(we.contentLength());\r
- file.setMimetype(we.contentType());\r
- file.setModificationTimestamp(we.modifiedTimesamp());\r
- file.setLastSyncDate(mCurrentSyncTime);\r
- return file;\r
- }\r
\r
\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
- i.putExtra(FileSyncService.SYNC_RESULT, result);\r
- }*/\r
- getContext().sendStickyBroadcast(i);\r
- }\r
- \r
/**\r
* Called by system SyncManager when a synchronization is required to be cancelled.\r
* \r
mCancellation = true;\r
super.onSyncCanceled();\r
}\r
-\r
+ \r
\r
/**\r
- * Logs an exception triggered in a synchronization request. \r
- * \r
- * @param e Caught exception.\r
- * @param uri Uri to the remote directory that was fetched when the synchronization failed \r
+ * Updates the locally stored version value of the ownCloud server\r
*/\r
- private void logException(Exception e, String uri) {\r
- if (e instanceof IOException) {\r
- Log.e(TAG, "Unrecovered transport exception while synchronizing " + uri + " at " + getAccount().name, e);\r
-\r
- } else if (e instanceof DavException) {\r
- Log.e(TAG, "Unexpected WebDAV exception while synchronizing " + uri + " at " + getAccount().name, e);\r
-\r
- } else {\r
- Log.e(TAG, "Unexpected exception while synchronizing " + uri + " at " + getAccount().name, e);\r
- }\r
- }\r
-\r
private void updateOCVersion() {\r
String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);\r
statUrl += AccountUtils.STATUS_PATH;\r
Log.e(TAG, "Problem getting response from server", e);\r
}\r
}\r
+\r
+ \r
+ \r
+ /**\r
+ * Synchronize the properties of files and folders contained in a remote folder given by remotePath.\r
+ * \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
+ \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
+ return;\r
+ }\r
+ \r
+ // perform folder synchronization\r
+ SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath, \r
+ mCurrentSyncTime, \r
+ parentId, \r
+ getStorageManager(), \r
+ getAccount(), \r
+ getContext()\r
+ );\r
+ RemoteOperationResult result = synchFolderOp.execute(client);\r
+ \r
+ \r
+ // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
+ sendStickyBroadcast(true, remotePath);\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
+ \r
+ } else {\r
+ if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
+ syncResult.stats.numAuthExceptions++;\r
+ \r
+ } else if (result.getException() instanceof DavException) {\r
+ syncResult.stats.numParseExceptions++;\r
+ \r
+ } else if (result.getException() instanceof IOException) { \r
+ syncResult.stats.numIoExceptions++;\r
+ \r
+ } else if (result.getException() != null) {\r
+ // TODO maybe something smarter with syncResult\r
+ mRightSync = false;\r
+ }\r
+ }\r
+ \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
+ 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
+ }\r
+ }\r
+ if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");\r
+ }\r
+\r
+ \r
+ /**\r
+ * Sends a message to any app 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
+ 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
+ i.putExtra(FileSyncService.SYNC_RESULT, result);\r
+ }*/\r
+ getContext().sendStickyBroadcast(i);\r
+ }\r
+\r
+ \r
+ \r
+ /**\r
+ * Notifies the user about a failed synchronization through the status notification bar \r
+ */\r
+ private void notifyFailedSynchronization() {\r
+ Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());\r
+ notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
+ // TODO put something smart in the contentIntent below\r
+ notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
+ notification.setLatestEventInfo(getContext().getApplicationContext(), \r
+ getContext().getString(R.string.sync_fail_ticker), \r
+ String.format(getContext().getString(R.string.sync_fail_content), getAccount().name), \r
+ notification.contentIntent);\r
+ ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
+ }\r
+\r
+ \r
+\r
}\r