Modify OwncloudFileObserver for enforcing watching the file when an external app...
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileObserverService.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.files.services;
20
21 import java.io.File;
22 import java.util.HashMap;
23 import java.util.Map;
24
25 import android.accounts.Account;
26 import android.accounts.AccountManager;
27 import android.app.Service;
28 import android.content.BroadcastReceiver;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.IntentFilter;
32 import android.database.Cursor;
33 import android.os.Binder;
34 import android.os.Handler;
35 import android.os.IBinder;
36
37 import com.owncloud.android.MainApp;
38 import com.owncloud.android.datamodel.FileDataStorageManager;
39 import com.owncloud.android.datamodel.OCFile;
40 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
41 import com.owncloud.android.files.OwnCloudFileObserver;
42 import com.owncloud.android.operations.SynchronizeFileOperation;
43 import com.owncloud.android.utils.FileStorageUtils;
44 import com.owncloud.android.utils.Log_OC;
45
46 public class FileObserverService extends Service {
47
48 public final static int CMD_INIT_OBSERVED_LIST = 1;
49 public final static int CMD_ADD_OBSERVED_FILE = 2;
50 public final static int CMD_DEL_OBSERVED_FILE = 3;
51
52 public final static String KEY_FILE_CMD = "KEY_FILE_CMD";
53 public final static String KEY_CMD_ARG_FILE = "KEY_CMD_ARG_FILE";
54 public final static String KEY_CMD_ARG_ACCOUNT = "KEY_CMD_ARG_ACCOUNT";
55
56 private static String TAG = FileObserverService.class.getSimpleName();
57
58 private static Map<String, OwnCloudFileObserver> mObserversMap;
59 private static DownloadCompletedReceiverBis mDownloadReceiver;
60 private IBinder mBinder = new LocalBinder();
61 private Handler mHandler = new Handler();
62
63 public class LocalBinder extends Binder {
64 FileObserverService getService() {
65 return FileObserverService.this;
66 }
67 }
68
69 @Override
70 public void onCreate() {
71 super.onCreate();
72 mDownloadReceiver = new DownloadCompletedReceiverBis();
73
74 IntentFilter filter = new IntentFilter();
75 filter.addAction(FileDownloader.getDownloadAddedMessage());
76 filter.addAction(FileDownloader.getDownloadFinishMessage());
77 registerReceiver(mDownloadReceiver, filter);
78
79 mObserversMap = new HashMap<String, OwnCloudFileObserver>();
80 //initializeObservedList();
81 }
82
83
84 @Override
85 public void onDestroy() {
86 unregisterReceiver(mDownloadReceiver);
87 mObserversMap = null; // TODO study carefully the life cycle of Services to grant the best possible observance
88 Log_OC.d(TAG, "Bye, bye");
89 super.onDestroy();
90 }
91
92
93 @Override
94 public IBinder onBind(Intent intent) {
95 return mBinder;
96 }
97
98 @Override
99 public int onStartCommand(Intent intent, int flags, int startId) {
100 // this occurs when system tries to restart
101 // service, so we need to reinitialize observers
102 if (intent == null) {
103 initializeObservedList();
104 return Service.START_STICKY;
105 }
106
107 if (!intent.hasExtra(KEY_FILE_CMD)) {
108 Log_OC.e(TAG, "No KEY_FILE_CMD argument given");
109 return Service.START_STICKY;
110 }
111
112 switch (intent.getIntExtra(KEY_FILE_CMD, -1)) {
113 case CMD_INIT_OBSERVED_LIST:
114 initializeObservedList();
115 break;
116 case CMD_ADD_OBSERVED_FILE:
117 addObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
118 (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
119 break;
120 case CMD_DEL_OBSERVED_FILE:
121 removeObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
122 (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
123 break;
124 default:
125 Log_OC.wtf(TAG, "Incorrect key given");
126 }
127
128 return Service.START_STICKY;
129 }
130
131
132 /**
133 * Read from the local database the list of files that must to be kept synchronized and
134 * starts file observers to monitor local changes on them
135 */
136 private void initializeObservedList() {
137 mObserversMap.clear();
138 Cursor c = getContentResolver().query(
139 ProviderTableMeta.CONTENT_URI,
140 null,
141 ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
142 new String[] {String.valueOf(1)},
143 null);
144 if (c == null || !c.moveToFirst()) return;
145 AccountManager acm = AccountManager.get(this);
146 Account[] accounts = acm.getAccountsByType(MainApp.getAccountType());
147 do {
148 Account account = null;
149 for (Account a : accounts)
150 if (a.name.equals(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER)))) {
151 account = a;
152 break;
153 }
154
155 if (account == null) continue;
156 FileDataStorageManager storage =
157 new FileDataStorageManager(account, getContentResolver());
158 if (!storage.fileExists(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))))
159 continue;
160
161 String path = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
162 if (path == null || path.length() <= 0)
163 continue;
164 OwnCloudFileObserver observer = new OwnCloudFileObserver(path, account, getApplicationContext(), mHandler);
165 mObserversMap.put(path, observer);
166 if (new File(path).exists()) {
167 observer.startWatching();
168 Log_OC.d(TAG, "Started watching file " + path);
169 }
170
171 } while (c.moveToNext());
172 c.close();
173 }
174
175
176 /**
177 * Registers the local copy of a remote file to be observed for local changes,
178 * an automatically updated in the ownCloud server.
179 *
180 * This method does NOT perform a {@link SynchronizeFileOperation} over the file.
181 *
182 * TODO We are ignoring that, currently, a local file can be linked to different files
183 * in ownCloud if it's uploaded several times. That's something pending to update: we
184 * will avoid that the same local file is linked to different remote files.
185 *
186 * @param file Object representing a remote file which local copy must be observed.
187 * @param account OwnCloud account containing file.
188 */
189 private void addObservedFile(OCFile file, Account account) {
190 if (file == null) {
191 Log_OC.e(TAG, "Trying to add a NULL file to observer");
192 return;
193 }
194 String localPath = file.getStoragePath();
195 if (localPath == null || localPath.length() <= 0) { // file downloading / to be download for the first time
196 localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
197 }
198 OwnCloudFileObserver observer = mObserversMap.get(localPath);
199 if (observer == null) {
200 /// the local file was never registered to observe before
201 observer = new OwnCloudFileObserver( localPath,
202 account,
203 getApplicationContext(),
204 mHandler);
205 mObserversMap.put(localPath, observer);
206 Log_OC.d(TAG, "Observer added for path " + localPath);
207
208 if (file.isDown()) {
209 observer.startWatching();
210 Log_OC.d(TAG, "Started watching " + localPath);
211 } // else - the observance can't be started on a file not already down; mDownloadReceiver will get noticed when the download of the file finishes
212 }
213
214 }
215
216
217 /**
218 * Unregisters the local copy of a remote file to be observed for local changes.
219 *
220 * Starts to watch it, if the file has a local copy to watch.
221 *
222 * TODO We are ignoring that, currently, a local file can be linked to different files
223 * in ownCloud if it's uploaded several times. That's something pending to update: we
224 * will avoid that the same local file is linked to different remote files.
225 *
226 * @param file Object representing a remote file which local copy must be not observed longer.
227 * @param account OwnCloud account containing file.
228 */
229 private void removeObservedFile(OCFile file, Account account) {
230 if (file == null) {
231 Log_OC.e(TAG, "Trying to remove a NULL file");
232 return;
233 }
234 String localPath = file.getStoragePath();
235 if (localPath == null || localPath.length() <= 0) {
236 localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
237 }
238
239 OwnCloudFileObserver observer = mObserversMap.get(localPath);
240 if (observer != null) {
241 observer.stopWatching();
242 mObserversMap.remove(observer);
243 Log_OC.d(TAG, "Stopped watching " + localPath);
244 }
245
246 }
247
248
249 /**
250 * Private receiver listening to events broadcast by the FileDownloader service.
251 *
252 * Starts and stops the observance on registered files when they are being download,
253 * in order to avoid to start unnecessary synchronizations.
254 */
255 private class DownloadCompletedReceiverBis extends BroadcastReceiver {
256
257 @Override
258 public void onReceive(Context context, Intent intent) {
259 String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH);
260 OwnCloudFileObserver observer = mObserversMap.get(downloadPath);
261 if (observer != null) {
262 if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage()) &&
263 new File(downloadPath).exists()) { // the download could be successful. not; in both cases, the file could be down, due to a former download or upload
264 observer.startWatching();
265 Log_OC.d(TAG, "Watching again " + downloadPath);
266
267 } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
268 observer.stopWatching();
269 Log_OC.d(TAG, "Disabling observance of " + downloadPath);
270 }
271 }
272 }
273
274 }
275
276 }