/* ownCloud Android client application
* Copyright (C) 2012 Bartek Przybylski
+ * Copyright (C) 2012-2013 ownCloud Inc.
*
* 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.
+ * it under the terms of the GNU General Public License version 2,
+ * as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
package com.owncloud.android.files.services;
import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
-import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.MainApp;
+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.OwnCloudFileObserver.FileObserverStatusListener;
-import com.owncloud.android.operations.RemoteOperationResult;
-import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
-import com.owncloud.android.ui.activity.ConflictsResolveActivity;
+import com.owncloud.android.operations.SynchronizeFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
+import com.owncloud.android.utils.Log_OC;
+
import android.accounts.Account;
-import android.accounts.AccountManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
-import android.os.Binder;
import android.os.IBinder;
-import android.util.Log;
-public class FileObserverService extends Service implements FileObserverStatusListener {
+/**
+ * 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.
+ *
+ * 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 {
+
+ public final static String MY_NAME = FileObserverService.class.getCanonicalName();
+ public final static String ACTION_INIT_OBSERVED_LIST = MY_NAME + ".action.INIT_OBSERVED_LIST";
+ public final static String CMD_ADD_OBSERVED_FILE = MY_NAME + ".action.ADD_OBSERVED_FILE";
+ public final static String CMD_DEL_OBSERVED_FILE = MY_NAME + ".action.DEL_OBSERVED_FILE";
- public final static String KEY_FILE_CMD = "KEY_FILE_CMD";
public final static String KEY_CMD_ARG_FILE = "KEY_CMD_ARG_FILE";
public final static String KEY_CMD_ARG_ACCOUNT = "KEY_CMD_ARG_ACCOUNT";
- public final static int CMD_INIT_OBSERVED_LIST = 1;
- public final static int CMD_ADD_OBSERVED_FILE = 2;
- public final static int CMD_DEL_OBSERVED_FILE = 3;
- public final static int CMD_ADD_DOWNLOADING_FILE = 4;
-
private static String TAG = FileObserverService.class.getSimpleName();
- private static List<OwnCloudFileObserver> mObservers;
- private static List<DownloadCompletedReceiver> mDownloadReceivers;
- private static Object mReceiverListLock = new Object();
- private IBinder mBinder = new LocalBinder();
- public class LocalBinder extends Binder {
- FileObserverService getService() {
- return FileObserverService.this;
+ private static Map<String, OwnCloudFileObserver> mObserversMap;
+ //private static Map<String, OwnCloudFileObserver> mObserverParentsMap;
+ private static DownloadCompletedReceiver mDownloadReceiver;
+
+
+ /**
+ * 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.
+ */
+ 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.
+ *
+ * @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) {
+ Intent intent = new Intent(context, FileObserverService.class);
+ 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());
+ registerReceiver(mDownloadReceiver, filter);
+
+ mObserversMap = new HashMap<String, OwnCloudFileObserver>();
+ //mObserverParentsMap = new HashMap<String, OwnCloudFileObserver>();
+ }
+
+
+ @Override
+ public void onDestroy() {
+ Log_OC.d(TAG, "onDestroy - FINISHING OBSERVATION");
+
+ unregisterReceiver(mDownloadReceiver);
+
+ Iterator<OwnCloudFileObserver> it = mObserversMap.values().iterator();
+ while (it.hasNext()) {
+ it.next().stopWatching();
}
+ mObserversMap.clear();
+ mObserversMap = null;
+
+ //mObserverParentsMap = null;
+
+ super.onDestroy();
}
+
@Override
public IBinder onBind(Intent intent) {
- return mBinder;
+ // this service cannot be bound
+ return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
- // this occurs when system tries to restart
- // service, so we need to reinitialize observers
- if (intent == null) {
+ 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
+ // was killed
initializeObservedList();
return Service.START_STICKY;
- }
- if (!intent.hasExtra(KEY_FILE_CMD)) {
- Log.e(TAG, "No KEY_FILE_CMD argument given");
- return Service.START_STICKY;
- }
-
- switch (intent.getIntExtra(KEY_FILE_CMD, -1)) {
- case CMD_INIT_OBSERVED_LIST:
- initializeObservedList();
- break;
- case CMD_ADD_OBSERVED_FILE:
- addObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
- (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
- break;
- case CMD_DEL_OBSERVED_FILE:
- removeObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
- (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
- break;
- case CMD_ADD_DOWNLOADING_FILE:
- addDownloadingFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
- (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
- break;
- default:
- Log.wtf(TAG, "Incorrect key given");
+ } else if (CMD_ADD_OBSERVED_FILE.equals(intent.getAction())) {
+ addObservedFile(
+ (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
+ (Account)intent.getParcelableExtra(KEY_CMD_ARG_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)
+ );
+
+ } 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
+ */
private void initializeObservedList() {
- if (mObservers != null) return; // nothing to do here
- mObservers = new ArrayList<OwnCloudFileObserver>();
- mDownloadReceivers = new ArrayList<DownloadCompletedReceiver>();
- Cursor c = getContentResolver().query(
+ 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);
- if (!c.moveToFirst()) return;
- AccountManager acm = AccountManager.get(this);
- Account[] accounts = acm.getAccounts();
- do {
- Account account = null;
- for (Account a : accounts)
- if (a.name.equals(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER)))) {
- account = a;
- break;
- }
+ null
+ );
+
+ if (cursorOnKeptInSync != null) {
+
+ if (cursorOnKeptInSync.moveToFirst()) {
+
+ String localPath = "";
+ //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)
+ );
+ /*
+ remotePath = cursorOnKeptInSync.getString(
+ cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_PATH)
+ );
+ */
+
+ account = new Account(accountName, MainApp.getAccountType());
+ if (!AccountUtils.exists(account, this) ||
+ localPath == null || localPath.length() <= 0) {
+ continue;
+ }
- if (account == null) continue;
- FileDataStorageManager storage =
- new FileDataStorageManager(account, getContentResolver());
- if (!storage.fileExists(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))))
- continue;
+ OwnCloudFileObserver observer = mObserversMap.get(localPath);
+ if (observer == null) {
+ observer = new OwnCloudFileObserver(
+ localPath, account, getApplicationContext()
+ );
+ 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 =
+ new OwnCloudFileObserver( parentPath,
+ account,
+ getApplicationContext());
+ mObserverParentsMap.put(parentPath, observer);
+
+ if (new File(localPath).exists()) {
+ observer.startWatching();
+ Log_OC.d(TAG, "Started watching file " + localPath);
+ observerParent.startWatching();
+ Log_OC.d(TAG, "Started watching parent file " + parentPath);
+ }
+ */
+
+ } while (cursorOnKeptInSync.moveToNext());
+
+ }
+ cursorOnKeptInSync.close();
+ }
+
+ // service does not stopSelf() ; that way it tries to be alive forever
- String path = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
- OwnCloudFileObserver observer =
- new OwnCloudFileObserver(path, OwnCloudFileObserver.CHANGES_ONLY);
- observer.setContext(getApplicationContext());
- observer.setAccount(account);
- observer.setStorageManager(storage);
- observer.setOCFile(storage.getFileByPath(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))));
- observer.addObserverStatusListener(this);
- observer.startWatching();
- mObservers.add(observer);
- Log.d(TAG, "Started watching file " + path);
-
- } while (c.moveToNext());
- c.close();
}
+
/**
* Registers the local copy of a remote file to be observed for local changes,
* an automatically updated in the ownCloud server.
- *
- * If there is no local copy of the remote file, a request to download it is send
- * to the FileDownloader service. The observation is delayed until the download
- * is finished.
*
+ * 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.e(TAG, "Trying to observe a NULL file");
+ Log_OC.e(TAG, "Trying to add a NULL file to observer");
return;
}
- if (mObservers == null) {
- // this is very rare case when service was killed by system
- // and observers list was deleted in that procedure
- initializeObservedList();
+ if (account == null) {
+ Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
+ return;
}
+
String localPath = file.getStoragePath();
- if (!file.isDown()) {
- // this is a file downloading / to be download for the first time
+ if (localPath == null || localPath.length() <= 0) {
+ // file downloading or to be downloaded for the first time
localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
}
- OwnCloudFileObserver tmpObserver = null, observer = null;
- for (int i = 0; i < mObservers.size(); ++i) {
- tmpObserver = mObservers.get(i);
- if (tmpObserver.getPath().equals(localPath)) {
- observer = tmpObserver;
- }
- tmpObserver.setContext(getApplicationContext()); // 'refreshing' context to all the observers? why?
- }
+ OwnCloudFileObserver observer = mObserversMap.get(localPath);
if (observer == null) {
/// the local file was never registered to observe before
- observer = new OwnCloudFileObserver(localPath, OwnCloudFileObserver.CHANGES_ONLY);
- //Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
- observer.setAccount(account);
- FileDataStorageManager storage =
- new FileDataStorageManager(account, getContentResolver()); // I don't trust in this resolver's life span...
- observer.setStorageManager(storage);
- //observer.setOCFile(storage.getFileByLocalPath(path)); // ISSUE 10 - the fix in FileDetailsFragment to avoid path == null was not enough; it the file was never down before, this sets a NULL OCFile in the observer
- observer.setOCFile(file);
- observer.addObserverStatusListener(this);
- observer.setContext(getApplicationContext());
+ observer = new OwnCloudFileObserver( localPath,
+ account,
+ getApplicationContext(),
+ mHandler);
+ mObserversMap.put(localPath, observer);
+ Log_OC.d(TAG, "Observer added for path " + localPath);
- } else {
- /* LET'S IGNORE THAT, CURRENTLY, A LOCAL FILE CAN BE LINKED TO DIFFERENT FILES IN OWNCLOUD;
- * we should change that
- *
- /// the local file is already observed for some other OCFile(s)
- observer.addOCFile(account, file); // OCFiles should have a reference to the account containing them to not be confused
- */
- }
-
- mObservers.add(observer);
- Log.d(TAG, "Observer added for path " + localPath);
+ /*
+ String parentPath = (new File(localPath)).getParent();
+ OwnCloudFileObserver observerParent =
+ new OwnCloudFileObserver( parentPath,
+ account,
+ getApplicationContext());
+ mObserverParentsMap.put(parentPath, observer);
+ */
- if (!file.isDown()) {
- // if the file is not down, it can't be observed for changes
- DownloadCompletedReceiver receiver = new DownloadCompletedReceiver(localPath, observer);
- registerReceiver(receiver, new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE));
-
- Intent i = new Intent(this, FileDownloader.class);
- i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
- i.putExtra(FileDownloader.EXTRA_FILE, file);
- startService(i);
-
- } else {
- observer.startWatching();
- Log.d(TAG, "Started watching " + localPath);
-
+ if (file.isDown()) {
+ observer.startWatching();
+ Log_OC.d(TAG, "Started watching " + localPath);
+ /*observerParent.startWatching();
+ Log_OC.d(TAG, "Started watching parent file " + parentPath);*/
+ }
+ // else - the observance can't be started on a file not already down;
+ // mDownloadReceiver will get noticed when the download of the file finishes
}
}
/**
* 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.
*/
private void removeObservedFile(OCFile file, Account account) {
+ Log_OC.v(TAG, "Removing a file from being watched");
+
if (file == null) {
- Log.e(TAG, "Trying to unobserve a NULL file");
+ Log_OC.e(TAG, "Trying to remove a NULL file");
return;
}
- if (mObservers == null) {
- initializeObservedList();
+ if (account == null) {
+ Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
+ return;
}
+
String localPath = file.getStoragePath();
- if (!file.isDown()) {
- // this happens when a file not in the device is set to be kept synchronized, and quickly unset again,
- // while the download is not finished
+ if (localPath == null || localPath.length() <= 0) {
localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
}
- for (int i = 0; i < mObservers.size(); ++i) {
- OwnCloudFileObserver observer = mObservers.get(i);
- if (observer.getPath().equals(localPath)) {
- observer.stopWatching();
- mObservers.remove(i); // assuming, again, that a local file can be only linked to only ONE remote file; currently false
- if (!file.isDown()) {
- // TODO unregister download receiver ;forget this until list of receivers is replaced for a single receiver
- }
- Log.d(TAG, "Stopped watching " + localPath);
- break;
- }
+ 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);
}
}
-
+
/**
- * Temporarily disables the observance of a file that is going to be download.
- *
- * @param file Object representing the remote file which local copy must not be observed temporarily.
- * @param account OwnCloud account containing file.
+ * 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.
*/
- private void addDownloadingFile(OCFile file, Account account) {
- OwnCloudFileObserver observer = null;
- for (OwnCloudFileObserver o : mObservers) {
- if (o.getRemotePath().equals(file.getRemotePath()) && o.getAccount().equals(account)) {
- observer = o;
- break;
- }
- }
- if (observer == null) {
- Log.e(TAG, "Couldn't find observer for remote file " + file.getRemotePath());
- return;
- }
- observer.stopWatching();
- DownloadCompletedReceiver dcr = new DownloadCompletedReceiver(observer.getPath(), observer);
- registerReceiver(dcr, new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE));
- }
-
-
- private static void addReceiverToList(DownloadCompletedReceiver r) {
- synchronized(mReceiverListLock) {
- mDownloadReceivers.add(r);
- }
- }
-
- private static void removeReceiverFromList(DownloadCompletedReceiver r) {
- synchronized(mReceiverListLock) {
- mDownloadReceivers.remove(r);
- }
- }
-
- @Override
- public void onObservedFileStatusUpdate(String localPath, String remotePath, Account account, RemoteOperationResult result) {
- if (!result.isSuccess()) {
- 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(getApplicationContext(), ConflictsResolveActivity.class);
- i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
- i.putExtra("remotepath", remotePath);
- i.putExtra("localpath", localPath);
- i.putExtra("account", account);
- startActivity(i);
-
- } else {
- // TODO send notification to the notification bar?
- }
- } // else, nothing else to do; now it's duty of FileUploader service
- }
-
private class DownloadCompletedReceiver extends BroadcastReceiver {
- String mPath;
- OwnCloudFileObserver mObserver;
-
- public DownloadCompletedReceiver(String path, OwnCloudFileObserver observer) {
- mPath = path;
- mObserver = observer;
- addReceiverToList(this);
- }
@Override
public void onReceive(Context context, Intent intent) {
- if (mPath.equals(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH))) {
- if ((new File(mPath)).exists()) {
- // the download could be successful, or not; in both cases, the file could be down, due to a former download or upload
- context.unregisterReceiver(this);
- removeReceiverFromList(this);
- mObserver.startWatching();
- Log.d(TAG, "Started watching " + mPath);
- return;
- } // else - keep waiting for a future retry of the download ;
- // mObserver.startWatching() won't ever work if the file is not in the device when it's called
+ Log_OC.d(TAG, "Received broadcast intent " + intent);
+
+ String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH);
+ OwnCloudFileObserver observer = mObserversMap.get(downloadPath);
+ if (observer != null) {
+ /*String parentPath = (new File(downloadPath)).getParent();
+ OwnCloudFileObserver observerParent = mObserverParentsMap.get(parentPath); */
+ 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);
+ /*observerParent.startWatching();
+ Log_OC.d(TAG, "Watching parent again " + parentPath); */
+
+ } 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);
}
}
- @Override
- public boolean equals(Object o) {
- if (o instanceof DownloadCompletedReceiver)
- return mPath.equals(((DownloadCompletedReceiver)o).mPath);
- return super.equals(o);
- }
}
+
}