Watch for replacements of favorite file besides than direct notifications
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileObserverService.java
index 4d6dd02..a602f8c 100644 (file)
-package com.owncloud.android.files.services;
+/* 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 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
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
 
-import java.util.ArrayList;
-import java.util.List;
+package com.owncloud.android.files.services;
 
-import com.owncloud.android.AccountUtils;
-import com.owncloud.android.datamodel.FileDataStorageManager;
-import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
-import com.owncloud.android.files.OwnCloudFileObserver;
+import java.io.File;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
 
 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.FileObserver;
 import android.os.IBinder;
-import android.util.Log;
 
+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.OwnCloudFolderObserver;
+import com.owncloud.android.operations.SynchronizeFileOperation;
+import com.owncloud.android.utils.FileStorageUtils;
+import com.owncloud.android.utils.Log_OC;
+
+
+/**
+ * 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 KEY_FILE_CMD = "KEY_FILE_CMD";
-    public final static String KEY_CMD_ARG = "KEY_CMD_ARG";
+    public final static String MY_NAME = FileObserverService.class.getCanonicalName();
+    public final static String ACTION_START_OBSERVE = MY_NAME + ".action.START_OBSERVATION";
+    public final static String ACTION_ADD_OBSERVED_FILE = MY_NAME + ".action.ADD_OBSERVED_FILE";
+    public final static String ACTION_DEL_OBSERVED_FILE = MY_NAME + ".action.DEL_OBSERVED_FILE";
+
+    private final static String ARG_FILE = "ARG_FILE";
+    private final static String ARG_ACCOUNT = "ARG_ACCOUNT";
+
+    private static String TAG = FileObserverService.class.getSimpleName();
+
+    private Map<String, OwnCloudFolderObserver> mFolderObserversMap;
+    private DownloadCompletedReceiver mDownloadReceiver;
+
+    /**
+     * Factory method to create intents that allow to start an
+     * ACTION_START_OBSERVE command.
+     * 
+     * @param context Android context of the caller component.
+     * @return Intent that starts a command ACTION_START_OBSERVE when
+     *         {@link Context#startService(Intent)} is called.
+     */
+    public static Intent makeInitIntent(Context context) {
+        Intent i = new Intent(context, FileObserverService.class);
+        i.setAction(ACTION_START_OBSERVE);
+        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.ACTION_ADD_OBSERVED_FILE
+                : FileObserverService.ACTION_DEL_OBSERVED_FILE);
+        intent.putExtra(FileObserverService.ARG_FILE, file);
+        intent.putExtra(FileObserverService.ARG_ACCOUNT, account);
+        return intent;
+    }
+
+    @Override
+    public void onCreate() {
+        Log_OC.d(TAG, "onCreate");
+        super.onCreate();
 
-    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;
+        mDownloadReceiver = new DownloadCompletedReceiver();
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(FileDownloader.getDownloadAddedMessage());
+        filter.addAction(FileDownloader.getDownloadFinishMessage());
+        registerReceiver(mDownloadReceiver, filter);
 
-    private static String TAG = "FileObserverService";
-    private static List<OwnCloudFileObserver> mObservers;
-    private static List<DownloadCompletedReceiver> mDownloadReceivers;
-    private static Object mReceiverListLock = new Object();
-    private IBinder mBinder = new LocalBinder();
+        mFolderObserversMap = new HashMap<String, OwnCloudFolderObserver>();
+    }
+
+    @Override
+    public void onDestroy() {
+        Log_OC.d(TAG, "onDestroy - finishing observation of favourite files");
 
-    public class LocalBinder extends Binder {
-        FileObserverService getService() {
-            return FileObserverService.this;
+        unregisterReceiver(mDownloadReceiver);
+
+        Iterator<OwnCloudFolderObserver> itOCFolder = mFolderObserversMap.values().iterator();
+        while (itOCFolder.hasNext()) {
+            itOCFolder.next().stopWatching();
         }
+        mFolderObserversMap.clear();
+        mFolderObserversMap = 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) {
-            initializeObservedList();
-            return Service.START_STICKY;
-        }
-            
-        if (!intent.hasExtra(KEY_FILE_CMD)) {
-            Log.e(TAG, "No KEY_FILE_CMD argument given");
+        Log_OC.d(TAG, "Starting command " + intent);
+
+        if (intent == null || ACTION_START_OBSERVE.equals(intent.getAction())) {
+            // NULL occurs when system tries to restart the service after its
+            // process was killed
+            startObservation();
             return Service.START_STICKY;
-        }
 
-        switch (intent.getIntExtra(KEY_FILE_CMD, -1)) {
-            case CMD_INIT_OBSERVED_LIST:
-                initializeObservedList();
-                break;
-            case CMD_ADD_OBSERVED_FILE:
-                addObservedFile(intent.getStringExtra(KEY_CMD_ARG));
-                break;
-            case CMD_DEL_OBSERVED_FILE:
-                removeObservedFile(intent.getStringExtra(KEY_CMD_ARG));
-                break;
-            default:
-                Log.wtf(TAG, "Incorrect key given");
+        } else if (ACTION_ADD_OBSERVED_FILE.equals(intent.getAction())) {
+            OCFile file = (OCFile) intent.getParcelableExtra(ARG_FILE);
+            Account account = (Account) intent.getParcelableExtra(ARG_ACCOUNT);
+            addObservedFile(file, account);
+
+        } else if (ACTION_DEL_OBSERVED_FILE.equals(intent.getAction())) {
+            removeObservedFile((OCFile) intent.getParcelableExtra(ARG_FILE),
+                    (Account) intent.getParcelableExtra(ARG_ACCOUNT));
+
+        } else {
+            Log_OC.e(TAG, "Unknown action recieved; ignoring it: " + intent.getAction());
         }
 
         return Service.START_STICKY;
     }
+
     
-    private void initializeObservedList() {
-        if (mObservers != null) return; // nothing to do here
-        mObservers = new ArrayList<OwnCloudFileObserver>();
-        mDownloadReceivers = new ArrayList<DownloadCompletedReceiver>();
-        Cursor c = getContentResolver().query(
-                ProviderTableMeta.CONTENT_URI,
+    /**
+     * Read from the local database the list of files that must to be kept
+     * synchronized and starts observers to monitor local changes on them
+     */
+    private void startObservation() {
+        Log_OC.d(TAG, "Loading all kept-in-sync files from database to start watching them");
+
+        // query for any favorite file in any OC account
+        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;
-                }
+                ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?", 
+                new String[] { String.valueOf(1) }, 
+                null
+        );
 
-            if (account == null) continue;
-            FileDataStorageManager storage =
-                    new FileDataStorageManager(account, getContentResolver());
-            if (!storage.fileExists(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))))
-                continue;
-
-            String path = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
-            OwnCloudFileObserver observer =
-                    new OwnCloudFileObserver(path, OwnCloudFileObserver.CHANGES_ONLY);
-            observer.setContext(getBaseContext());
-            observer.setAccount(account);
-            observer.setStorageManager(storage);
-            observer.setOCFile(storage.getFileByPath(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))));
-            observer.startWatching();
-            mObservers.add(observer);
-            Log.d(TAG, "Started watching file " + path);
-            
-        } while (c.moveToNext());
-        c.close();
-    }
-    
-    private void addObservedFile(String path) {
-        if (path == null) return;
-        if (mObservers == null) {
-            // this is very rare case when service was killed by system
-            // and observers list was deleted in that procedure
-            initializeObservedList();
-        }
-        boolean duplicate = false;
-        OwnCloudFileObserver observer = null;
-        for (int i = 0; i < mObservers.size(); ++i) {
-            observer = mObservers.get(i);
-            if (observer.getPath().equals(path))
-                duplicate = true;
-            observer.setContext(getBaseContext());
+        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;
+                    }
+                    
+                    addObservedFile(localPath, account);
+
+                } while (cursorOnKeptInSync.moveToNext());
+
+            }
+            cursorOnKeptInSync.close();
         }
-        if (duplicate) return;
-        observer = new OwnCloudFileObserver(path, OwnCloudFileObserver.CHANGES_ONLY);
-        observer.setContext(getBaseContext());
-        Account account = AccountUtils.getCurrentOwnCloudAccount(getBaseContext());
-        observer.setAccount(account);
-        FileDataStorageManager storage =
-                new FileDataStorageManager(account, getContentResolver());
-        observer.setStorageManager(storage);
-        observer.setOCFile(storage.getFileByLocalPath(path));
-
-        DownloadCompletedReceiver receiver = new DownloadCompletedReceiver(path, observer);
-        registerReceiver(receiver, new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE));
-
-        mObservers.add(observer);
-        Log.d(TAG, "Observer added for path " + path);
+
+        // service does not stopSelf() ; that way it tries to be alive forever
+
     }
+
     
-    private void removeObservedFile(String path) {
-        if (path == null) return;
-        if (mObservers == null) {
-            initializeObservedList();
+    /**
+     * 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.
+     */
+    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;
         }
-        for (int i = 0; i < mObservers.size(); ++i) {
-            OwnCloudFileObserver observer = mObservers.get(i);
-            if (observer.getPath().equals(path)) {
-                observer.stopWatching();
-                mObservers.remove(i);
-                break;
-            }
+        if (account == null) {
+            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) {
+            // file downloading or to be downloaded for the first time
+            localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
         }
-        Log.d(TAG, "Stopped watching " + path);
+        
+        addObservedFile(localPath, account);
+        
     }
+
+    
+    
     
-    private static void addReceiverToList(DownloadCompletedReceiver r) {
-        synchronized(mReceiverListLock) {
-            mDownloadReceivers.add(r);
+    /**
+     * Registers the folder to be observed in which there are changes inside any
+     * file
+     * 
+     * @param account OwnCloud account containing file.
+     */
+    private void addObservedFile(String localPath, Account account) {
+        File file = new File(localPath);
+        String parentPath = file.getParent();
+        OwnCloudFolderObserver observer = mFolderObserversMap.get(parentPath);
+        if (observer == null) {
+            observer = new OwnCloudFolderObserver(parentPath, account, getApplicationContext());
+            mFolderObserversMap.put(parentPath, observer);
+            Log_OC.d(TAG, "Observer added for parent folder " + parentPath + "/");
         }
+        
+        observer.startWatching(file.getName());
+        Log_OC.d(TAG, "Added " + localPath + " to list of observed children");
     }
+
     
-    private static void removeReceiverFromList(DownloadCompletedReceiver r) {
-        synchronized(mReceiverListLock) {
-            mDownloadReceivers.remove(r);
+    /**
+     * 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_OC.e(TAG, "Trying to remove a NULL file");
+            return;
+        }
+        if (account == null) {
+            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);
         }
+
+        removeObservedFile(localPath);
     }
+
     
-    private class DownloadCompletedReceiver extends BroadcastReceiver {
-        String mPath;
-        OwnCloudFileObserver mObserver;
+    private void removeObservedFile(String localPath) {
+        File file = new File(localPath);
+        String parentPath = file.getParent();
+        OwnCloudFolderObserver observer = mFolderObserversMap.get(parentPath);
+        if (observer != null) {
+            observer.stopWatching(file.getName());
+            if (observer.isEmpty()) {
+                mFolderObserversMap.remove(parentPath);
+                Log_OC.d(TAG, "Observer removed for parent folder " + parentPath + "/");
+            }
         
-        public DownloadCompletedReceiver(String path, OwnCloudFileObserver observer) {
-            mPath = path;
-            mObserver = observer;
-            addReceiverToList(this);
+        } else {
+            Log_OC.d(TAG, "No observer to remove for path " + localPath);
         }
-        
+    }
+
+    
+    /**
+     * Private receiver listening to events broadcasted by the FileDownloader service.
+     * 
+     * Pauses and resumes the observance on registered files while being download,
+     * in order to avoid to unnecessary synchronizations.
+     */
+    private class DownloadCompletedReceiver extends BroadcastReceiver {
+
         @Override
         public void onReceive(Context context, Intent intent) {
-            if (mPath.equals(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH))) {
-                context.unregisterReceiver(this);
-                removeReceiverFromList(this);
-                mObserver.startWatching();
-                Log.d(TAG, "Started watching " + mPath);
-                return;
+            Log_OC.d(TAG, "Received broadcast intent " + intent);
+
+            File downloadedFile = new File(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
+            String parentPath = downloadedFile.getParent();
+            OwnCloudFolderObserver observer = mFolderObserversMap.get(parentPath);
+            if (observer != null) {
+                if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage())
+                        && downloadedFile.exists()) {
+                    // no matter if the download was be successful or not; the
+                    // file could be down anyway due to a former download or upload
+                    observer.startWatching(downloadedFile.getName());
+                    Log_OC.d(TAG, "Resuming observance of " + downloadedFile.getAbsolutePath());
+
+                } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
+                    observer.stopWatching(downloadedFile.getName());
+                    Log_OC.d(TAG, "Pausing observance of " + downloadedFile.getAbsolutePath());
+                }
+
+            } else {
+                Log_OC.d(TAG, "No observer for path " + downloadedFile.getAbsolutePath());
             }
         }
-        
-        @Override
-        public boolean equals(Object o) {
-            if (o instanceof DownloadCompletedReceiver)
-                return mPath.equals(((DownloadCompletedReceiver)o).mPath);
-            return super.equals(o);
-        }
+
     }
+
 }