From: jabarros Date: Mon, 30 Jun 2014 13:13:34 +0000 (+0200) Subject: Create observer class for parent folders X-Git-Tag: oc-android-1.7.0_signed~256^2~5 X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/commitdiff_plain/dba9c3a64dec698d142eb6f1653d441db7e1573a?ds=inline Create observer class for parent folders --- diff --git a/src/com/owncloud/android/files/OwnCloudFolderObserver.java b/src/com/owncloud/android/files/OwnCloudFolderObserver.java new file mode 100644 index 00000000..2cb45519 --- /dev/null +++ b/src/com/owncloud/android/files/OwnCloudFolderObserver.java @@ -0,0 +1,83 @@ +package com.owncloud.android.files; + +import java.io.File; + +import android.accounts.Account; +import android.content.Context; +import android.content.Intent; +import android.os.FileObserver; + +import com.owncloud.android.datamodel.FileDataStorageManager; +import com.owncloud.android.datamodel.OCFile; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; +import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.operations.SynchronizeFileOperation; +import com.owncloud.android.ui.activity.ConflictsResolveActivity; +import com.owncloud.android.utils.Log_OC; + +public class OwnCloudFolderObserver extends FileObserver { + + private static int MASK = (FileObserver.CREATE | FileObserver.MOVED_TO); + + private static String TAG = OwnCloudFolderObserver.class.getSimpleName(); + + private String mPath; + private int mMask; + private Account mOCAccount; + private Context mContext; + + public OwnCloudFolderObserver(String path, Account account, Context context) { + super(path, FileObserver.ALL_EVENTS); + if (path == null) + throw new IllegalArgumentException("NULL path argument received"); + if (account == null) + throw new IllegalArgumentException("NULL account argument received"); + if (context == null) + throw new IllegalArgumentException("NULL context argument received"); + mPath = path; + mOCAccount = account; + mContext = context; + } + + @Override + public void onEvent(int event, String path) { + Log_OC.d(TAG, "Got file modified with event " + event + " and path " + mPath + + ((path != null) ? File.separator + path : "")); + if ((event & MASK) == 0) { + Log_OC.wtf(TAG, "Incorrect event " + event + " sent for file " + mPath + + ((path != null) ? File.separator + path : "") + " with registered for " + mMask + + " and original path " + mPath); + + } else { + if ((event & FileObserver.CREATE) != 0) { + // TODO Enable a flag + } + if ((event & FileObserver.MOVED_TO) != 0) { + // TODO Start sync + } + } + } + + private void startSyncOperation() { + // TODO Move to common file because it is being used in OCFileObserver + // too + + FileDataStorageManager storageManager = new FileDataStorageManager(mOCAccount, mContext.getContentResolver()); + // a fresh object is needed; many things could have occurred to the file + // since it was registered to observe again, assuming that local files + // are linked to a remote file AT MOST, SOMETHING TO BE DONE; + OCFile file = storageManager.getFileByLocalPath(mPath); + SynchronizeFileOperation sfo = new SynchronizeFileOperation(file, null, mOCAccount, true, mContext); + RemoteOperationResult result = sfo.execute(storageManager, mContext); + if (result.getCode() == ResultCode.SYNC_CONFLICT) { + // ISSUE 5: if the user is not running the app (this is a service!), + // this can be very intrusive; a notification should be preferred + Intent i = new Intent(mContext, ConflictsResolveActivity.class); + i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); + i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file); + i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mOCAccount); + mContext.startActivity(i); + } + } + +} diff --git a/src/com/owncloud/android/files/services/FileObserverService.java b/src/com/owncloud/android/files/services/FileObserverService.java index ab3d4f36..6d0c83e5 100644 --- a/src/com/owncloud/android/files/services/FileObserverService.java +++ b/src/com/owncloud/android/files/services/FileObserverService.java @@ -28,6 +28,7 @@ import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.db.ProviderMeta.ProviderTableMeta; import com.owncloud.android.files.OwnCloudFileObserver; +import com.owncloud.android.files.OwnCloudFolderObserver; import com.owncloud.android.operations.SynchronizeFileOperation; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -43,17 +44,18 @@ import android.database.Cursor; import android.os.IBinder; /** - * Service keeping a list of {@link FileObserver} instances that watch for local changes in - * favorite files (formerly known as kept-in-sync files) and try to synchronize them with the - * OC server as soon as possible. + * Service keeping a list of {@link FileObserver} instances that watch for local + * changes in favorite files (formerly known as kept-in-sync files) and try to + * synchronize them with the OC server as soon as possible. * - * Tries to be alive as long as possible; that is the reason why stopSelf() is never called. + * Tries to be alive as long as possible; that is the reason why stopSelf() is + * never called. + * + * It is expected that the system eventually kills the service when runs low of + * memory. To minimize the impact of this, the service always returns + * Service.START_STICKY, and the later restart of the service is explicitly + * considered in {@link FileObserverService#onStartCommand(Intent, int, int)}. * - * It is expected that the system eventually kills the service when runs low of memory. - * To minimize the impact of this, the service always returns Service.START_STICKY, and the later - * restart of the service is explicitly considered in - * {@link FileObserverService#onStartCommand(Intent, int, int)}. - * * @author David A. Velasco */ public class FileObserverService extends Service { @@ -69,90 +71,88 @@ public class FileObserverService extends Service { private static String TAG = FileObserverService.class.getSimpleName(); private static Map mObserversMap; - private static Map mObserverParentsMap; + private static Map mObserversFolderMap; private static DownloadCompletedReceiver mDownloadReceiver; - /** - * Factory method to create intents that allow to start an ACTION_INIT_OBSERVED_LIST command. + * Factory method to create intents that allow to start an + * ACTION_INIT_OBSERVED_LIST command. * - * @param context Android context of the caller component. - * @return Intent that starts a command ACTION_INIT_OBSERVED_LIST when - * {@link Context#startService(Intent)} is called. + * @param context Android context of the caller component. + * @return Intent that starts a command ACTION_INIT_OBSERVED_LIST when + * {@link Context#startService(Intent)} is called. */ public static Intent makeInitIntent(Context context) { Intent i = new Intent(context, FileObserverService.class); i.setAction(ACTION_INIT_OBSERVED_LIST); return i; } - - + /** - * Factory method to create intents that allow to start or stop the observance of a file. + * Factory method to create intents that allow to start or stop the + * observance of a file. * - * @param context Android context of the caller component. - * @param file OCFile to start or stop to watch. - * @param account OC account containing file. - * @param watchIt 'True' creates an intent to watch, 'false' an intent to stop watching. - * @return Intent to start or stop the observance of a file through a call - * to {@link Context#startService(Intent)}. + * @param context Android context of the caller component. + * @param file OCFile to start or stop to watch. + * @param account OC account containing file. + * @param watchIt 'True' creates an intent to watch, 'false' an intent to + * stop watching. + * @return Intent to start or stop the observance of a file through a call + * to {@link Context#startService(Intent)}. */ - public static Intent makeObservedFileIntent( - Context context, OCFile file, Account account, boolean watchIt) { + public static Intent makeObservedFileIntent(Context context, OCFile file, Account account, boolean watchIt) { Intent intent = new Intent(context, FileObserverService.class); - intent.setAction( - watchIt ? - FileObserverService.CMD_ADD_OBSERVED_FILE - : - FileObserverService.CMD_DEL_OBSERVED_FILE - ); + intent.setAction(watchIt ? FileObserverService.CMD_ADD_OBSERVED_FILE + : FileObserverService.CMD_DEL_OBSERVED_FILE); intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, file); intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, account); return intent; } - - - + @Override public void onCreate() { Log_OC.d(TAG, "onCreate"); super.onCreate(); - + mDownloadReceiver = new DownloadCompletedReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(FileDownloader.getDownloadAddedMessage()); - filter.addAction(FileDownloader.getDownloadFinishMessage()); + filter.addAction(FileDownloader.getDownloadFinishMessage()); registerReceiver(mDownloadReceiver, filter); - + mObserversMap = new HashMap(); - mObserverParentsMap = new HashMap(); + mObserversFolderMap = new HashMap(); } - - + + @Override + public void onLowMemory() { + Log_OC.d(TAG, "ON LOW MEMORY"); + + } + @Override public void onDestroy() { Log_OC.d(TAG, "onDestroy - FINISHING OBSERVATION"); - + unregisterReceiver(mDownloadReceiver); - + Iterator it = mObserversMap.values().iterator(); while (it.hasNext()) { it.next().stopWatching(); } mObserversMap.clear(); mObserversMap = null; - - it = mObserverParentsMap.values().iterator(); - while (it.hasNext()) { - it.next().stopWatching(); + + Iterator itOCFolder = mObserversFolderMap.values().iterator(); + while (itOCFolder.hasNext()) { + itOCFolder.next().stopWatching(); } - mObserverParentsMap.clear(); - mObserverParentsMap = null; - + mObserversFolderMap.clear(); + mObserversFolderMap = null; + super.onDestroy(); } - - + @Override public IBinder onBind(Intent intent) { // this service cannot be bound @@ -162,128 +162,125 @@ public class FileObserverService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { Log_OC.d(TAG, "Starting command " + intent); - + if (intent == null || ACTION_INIT_OBSERVED_LIST.equals(intent.getAction())) { - // NULL occurs when system tries to restart the service after its process + // NULL occurs when system tries to restart the service after its + // process // was killed initializeObservedList(); return Service.START_STICKY; - + } else if (CMD_ADD_OBSERVED_FILE.equals(intent.getAction())) { - addObservedFile( - (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE), - (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT) - ); - + OCFile file = (OCFile) intent.getParcelableExtra(KEY_CMD_ARG_FILE); + Account account = (Account) intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT); + addObservedFile(file, account); + + String localPath = file.getStoragePath(); + if (localPath == null || localPath.length() <= 0) { + // file downloading or to be downloaded for the first time + localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file); + } + + String parentPath = (new File(localPath)).getParent(); + + addObservedFolder(parentPath, account); + } else if (CMD_DEL_OBSERVED_FILE.equals(intent.getAction())) { - removeObservedFile( - (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE), - (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT) - ); - + removeObservedFile((OCFile) intent.getParcelableExtra(KEY_CMD_ARG_FILE), + (Account) intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT)); + } else { Log_OC.e(TAG, "Unknown action recieved; ignoring it: " + intent.getAction()); } - + return Service.START_STICKY; } - /** - * Read from the local database the list of files that must to be kept synchronized and - * starts file observers to monitor local changes on them + * Read from the local database the list of files that must to be kept + * synchronized and starts file observers to monitor local changes on them */ private void initializeObservedList() { Log_OC.d(TAG, "Loading all kept-in-sync files from database to start watching them"); - - //mObserversMap.clear(); - //mObserverParentsMap.clear(); - - Cursor cursorOnKeptInSync = getContentResolver().query( - ProviderTableMeta.CONTENT_URI, - null, - ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?", - new String[] {String.valueOf(1)}, - null - ); - + + // mObserversMap.clear(); + // mObserverParentsMap.clear(); + + Cursor cursorOnKeptInSync = getContentResolver().query(ProviderTableMeta.CONTENT_URI, null, + ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?", new String[] { String.valueOf(1) }, null); + if (cursorOnKeptInSync != null) { - + if (cursorOnKeptInSync.moveToFirst()) { - + String localPath = ""; - //String remotePath = ""; + // String remotePath = ""; String accountName = ""; Account account = null; do { - localPath = cursorOnKeptInSync.getString( - cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH) - ); - accountName = cursorOnKeptInSync.getString( - cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER) - ); + localPath = cursorOnKeptInSync.getString(cursorOnKeptInSync + .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)); + accountName = cursorOnKeptInSync.getString(cursorOnKeptInSync + .getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER)); /* - remotePath = cursorOnKeptInSync.getString( - cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_PATH) - ); - */ - + * remotePath = cursorOnKeptInSync.getString( + * cursorOnKeptInSync + * .getColumnIndex(ProviderTableMeta.FILE_PATH) ); + */ + account = new Account(accountName, MainApp.getAccountType()); - if (!AccountUtils.exists(account, this) || - localPath == null || localPath.length() <= 0) { + if (!AccountUtils.exists(account, this) || localPath == null || localPath.length() <= 0) { continue; } OwnCloudFileObserver observer = mObserversMap.get(localPath); if (observer == null) { - observer = new OwnCloudFileObserver( - localPath, account, getApplicationContext() - ); + observer = new OwnCloudFileObserver(localPath, account, getApplicationContext(), mHandler); mObserversMap.put(localPath, observer); - + // only if being added if (new File(localPath).exists()) { observer.startWatching(); Log_OC.d(TAG, "Started watching file " + localPath); } } - + String parentPath = (new File(localPath)).getParent(); - OwnCloudFileObserver observerParent = mObserverParentsMap.get(parentPath); - if (observerParent == null) { - observerParent = new OwnCloudFileObserver( - parentPath, account, getApplicationContext() - ); - mObserverParentsMap.put(parentPath, observer); + OwnCloudFolderObserver observerFolder = mObserversFolderMap.get(parentPath); + if (observerFolder == null) { + observerFolder = new OwnCloudFolderObserver(parentPath, account, getApplicationContext()); + mObserversFolderMap.put(parentPath, observerFolder); + if (new File(parentPath).exists()) { - observerParent.startWatching(); - Log_OC.d(TAG, "Started watching parent folder " + parentPath); + observerFolder.startWatching(); + Log_OC.d(TAG, "Started watching parent folder " + parentPath + "/"); } } - + } while (cursorOnKeptInSync.moveToNext()); - + } cursorOnKeptInSync.close(); } - - // service does not stopSelf() ; that way it tries to be alive forever + + // service does not stopSelf() ; that way it tries to be alive forever } - - + /** - * Registers the local copy of a remote file to be observed for local changes, - * an automatically updated in the ownCloud server. + * Registers the local copy of a remote file to be observed for local + * changes, an automatically updated in the ownCloud server. * - * This method does NOT perform a {@link SynchronizeFileOperation} over the file. - * - * @param file Object representing a remote file which local copy must be observed. - * @param account OwnCloud account containing file. + * This method does NOT perform a {@link SynchronizeFileOperation} over the + * file. + * + * @param file Object representing a remote file which local copy must be + * observed. + * @param account OwnCloud account containing file. */ private void addObservedFile(OCFile file, Account account) { Log_OC.v(TAG, "Adding a file to be watched"); - + if (file == null) { Log_OC.e(TAG, "Trying to add a NULL file to observer"); return; @@ -292,58 +289,67 @@ public class FileObserverService extends Service { Log_OC.e(TAG, "Trying to add a file with a NULL account to observer"); return; } - + String localPath = file.getStoragePath(); - if (localPath == null || localPath.length() <= 0) { + if (localPath == null || localPath.length() <= 0) { // file downloading or to be downloaded for the first time localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file); } OwnCloudFileObserver observer = mObserversMap.get(localPath); if (observer == null) { - /// the local file was never registered to observe before - observer = new OwnCloudFileObserver( - localPath, account, getApplicationContext() - ); + // / the local file was never registered to observe before + observer = new OwnCloudFileObserver(localPath, account, getApplicationContext(), mHandler); mObserversMap.put(localPath, observer); Log_OC.d(TAG, "Observer added for path " + localPath); - + if (file.isDown()) { observer.startWatching(); Log_OC.d(TAG, "Started watching " + localPath); - } - // else - the observance can't be started on a file not already down; - // mDownloadReceiver will get noticed when the download of the file finishes + } + // else - the observance can't be started on a file not already + // down; + // mDownloadReceiver will get noticed when the download of the file + // finishes } - + } + + /** + * Registers the folder to be observed in which there are changes inside any + * file + * + * @param localPath String representing the folder will be observed + * @param account OwnCloud account containing file. + */ + public void addObservedFolder(String localPath, Account account) { + Log_OC.v(TAG, "Adding a child file to be watched"); + String parentPath = (new File(localPath)).getParent(); - OwnCloudFileObserver observerParent = mObserverParentsMap.get(parentPath); + OwnCloudFolderObserver observerParent = mObserversFolderMap.get(parentPath); if (observerParent == null) { - observerParent = new OwnCloudFileObserver( - parentPath, account, getApplicationContext() - ); - mObserverParentsMap.put(parentPath, observerParent); - Log_OC.d(TAG, "Observer added for parent folder " + localPath); - - if (file.isDown()) { + observerParent = new OwnCloudFolderObserver(parentPath, account, getApplicationContext()); + mObserversFolderMap.put(parentPath, observerParent); + Log_OC.d(TAG, "Observer added for parent folder " + parentPath + "/"); + + if (new File(parentPath).exists()) { observerParent.startWatching(); - Log_OC.d(TAG, "Started watching parent folder " + parentPath); - } + Log_OC.d(TAG, "Started watching parent folder " + parentPath + "/"); + } } - } - /** - * Unregisters the local copy of a remote file to be observed for local changes. - * + * Unregisters the local copy of a remote file to be observed for local + * changes. + * * Starts to watch it, if the file has a local copy to watch. * - * @param file Object representing a remote file which local copy must be not observed longer. - * @param account OwnCloud account containing file. + * @param file Object representing a remote file which local copy must be + * not observed longer. + * @param account OwnCloud account containing file. */ private void removeObservedFile(OCFile file, Account account) { Log_OC.v(TAG, "Removing a file from being watched"); - + if (file == null) { Log_OC.e(TAG, "Trying to remove a NULL file"); return; @@ -352,33 +358,33 @@ public class FileObserverService extends Service { Log_OC.e(TAG, "Trying to add a file with a NULL account to observer"); return; } - + String localPath = file.getStoragePath(); if (localPath == null || localPath.length() <= 0) { localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file); } - + OwnCloudFileObserver observer = mObserversMap.get(localPath); if (observer != null) { observer.stopWatching(); mObserversMap.remove(observer); Log_OC.d(TAG, "Stopped watching " + localPath); - + } else { Log_OC.d(TAG, "No observer to remove for path " + localPath); } - - } + } /** - * Private receiver listening to events broadcast by the FileDownloader service. + * Private receiver listening to events broadcast by the FileDownloader + * service. * - * Starts and stops the observance on registered files when they are being download, - * in order to avoid to start unnecessary synchronizations. + * Starts and stops the observance on registered files when they are being + * download, in order to avoid to start unnecessary synchronizations. */ private class DownloadCompletedReceiver extends BroadcastReceiver { - + @Override public void onReceive(Context context, Intent intent) { Log_OC.d(TAG, "Received broadcast intent " + intent); @@ -386,23 +392,24 @@ public class FileObserverService extends Service { String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH); OwnCloudFileObserver observer = mObserversMap.get(downloadPath); if (observer != null) { - if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage()) && - new File(downloadPath).exists()) { - // no matter is the download was be successful or not; the file could be down, - // anyway due to a former download or upload + if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage()) + && new File(downloadPath).exists()) { + // no matter is the download was be successful or not; the + // file could be down, + // anyway due to a former download or upload observer.startWatching(); Log_OC.d(TAG, "Resuming observance of " + downloadPath); - + } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) { observer.stopWatching(); Log_OC.d(TAG, "Pausing observance of " + downloadPath); } - + } else { Log_OC.d(TAG, "No observer for path " + downloadPath); } } - + } }