cb72cc47871f66835aee2afac6bc2017238e2b58
[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.Iterator;
24 import java.util.Map;
25
26 import com.owncloud.android.MainApp;
27 import com.owncloud.android.authentication.AccountUtils;
28 import com.owncloud.android.datamodel.OCFile;
29 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
30 import com.owncloud.android.files.OwnCloudFileObserver;
31 import com.owncloud.android.operations.SynchronizeFileOperation;
32 import com.owncloud.android.utils.FileStorageUtils;
33 import com.owncloud.android.utils.Log_OC;
34
35
36 import android.accounts.Account;
37 import android.app.Service;
38 import android.content.BroadcastReceiver;
39 import android.content.Context;
40 import android.content.Intent;
41 import android.content.IntentFilter;
42 import android.database.Cursor;
43 import android.os.IBinder;
44
45 /**
46 * Service keeping a list of {@link FileObserver} instances that watch for local changes in
47 * favorite files (formerly known as kept-in-sync files) and try to synchronize them with the
48 * OC server as soon as possible.
49 *
50 * Tries to be alive as long as possible; that is the reason why stopSelf() is never called.
51 *
52 * It is expected that the system eventually kills the service when runs low of memory.
53 * To minimize the impact of this, the service always returns Service.START_STICKY, and the later
54 * restart of the service is explicitly considered in
55 * {@link FileObserverService#onStartCommand(Intent, int, int)}.
56 *
57 * @author David A. Velasco
58 */
59 public class FileObserverService extends Service {
60
61 public final static String MY_NAME = FileObserverService.class.getCanonicalName();
62 public final static String ACTION_INIT_OBSERVED_LIST = MY_NAME + ".action.INIT_OBSERVED_LIST";
63 public final static String CMD_ADD_OBSERVED_FILE = MY_NAME + ".action.ADD_OBSERVED_FILE";
64 public final static String CMD_DEL_OBSERVED_FILE = MY_NAME + ".action.DEL_OBSERVED_FILE";
65
66 public final static String KEY_CMD_ARG_FILE = "KEY_CMD_ARG_FILE";
67 public final static String KEY_CMD_ARG_ACCOUNT = "KEY_CMD_ARG_ACCOUNT";
68
69 private static String TAG = FileObserverService.class.getSimpleName();
70
71 private static Map<String, OwnCloudFileObserver> mObserversMap;
72 //private static Map<String, OwnCloudFileObserver> mObserverParentsMap;
73 private static DownloadCompletedReceiver mDownloadReceiver;
74
75
76 /**
77 * Factory method to create intents that allow to start an ACTION_INIT_OBSERVED_LIST command.
78 *
79 * @param context Android context of the caller component.
80 * @return Intent that starts a command ACTION_INIT_OBSERVED_LIST when
81 * {@link Context#startService(Intent)} is called.
82 */
83 public static Intent makeInitIntent(Context context) {
84 Intent i = new Intent(context, FileObserverService.class);
85 i.setAction(ACTION_INIT_OBSERVED_LIST);
86 return i;
87 }
88
89
90 /**
91 * Factory method to create intents that allow to start or stop the observance of a file.
92 *
93 * @param context Android context of the caller component.
94 * @param file OCFile to start or stop to watch.
95 * @param account OC account containing file.
96 * @param watchIt 'True' creates an intent to watch, 'false' an intent to stop watching.
97 * @return Intent to start or stop the observance of a file through a call
98 * to {@link Context#startService(Intent)}.
99 */
100 public static Intent makeObservedFileIntent(
101 Context context, OCFile file, Account account, boolean watchIt) {
102 Intent intent = new Intent(context, FileObserverService.class);
103 intent.setAction(
104 watchIt ?
105 FileObserverService.CMD_ADD_OBSERVED_FILE
106 :
107 FileObserverService.CMD_DEL_OBSERVED_FILE
108 );
109 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, file);
110 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, account);
111 return intent;
112 }
113
114
115
116 @Override
117 public void onCreate() {
118 Log_OC.d(TAG, "onCreate");
119 super.onCreate();
120
121 mDownloadReceiver = new DownloadCompletedReceiver();
122 IntentFilter filter = new IntentFilter();
123 filter.addAction(FileDownloader.getDownloadAddedMessage());
124 filter.addAction(FileDownloader.getDownloadFinishMessage());
125 registerReceiver(mDownloadReceiver, filter);
126
127 mObserversMap = new HashMap<String, OwnCloudFileObserver>();
128 //mObserverParentsMap = new HashMap<String, OwnCloudFileObserver>();
129 }
130
131
132 @Override
133 public void onDestroy() {
134 Log_OC.d(TAG, "onDestroy - FINISHING OBSERVATION");
135
136 unregisterReceiver(mDownloadReceiver);
137
138 Iterator<OwnCloudFileObserver> it = mObserversMap.values().iterator();
139 while (it.hasNext()) {
140 it.next().stopWatching();
141 }
142 mObserversMap.clear();
143 mObserversMap = null;
144
145 //mObserverParentsMap = null;
146
147 super.onDestroy();
148 }
149
150
151 @Override
152 public IBinder onBind(Intent intent) {
153 // this service cannot be bound
154 return null;
155 }
156
157 @Override
158 public int onStartCommand(Intent intent, int flags, int startId) {
159 Log_OC.d(TAG, "Starting command " + intent);
160
161 if (intent == null || ACTION_INIT_OBSERVED_LIST.equals(intent.getAction())) {
162 // NULL occurs when system tries to restart the service after its process
163 // was killed
164 initializeObservedList();
165 return Service.START_STICKY;
166
167 } else if (CMD_ADD_OBSERVED_FILE.equals(intent.getAction())) {
168 addObservedFile(
169 (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
170 (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT)
171 );
172
173 } else if (CMD_DEL_OBSERVED_FILE.equals(intent.getAction())) {
174 removeObservedFile(
175 (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
176 (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT)
177 );
178
179 } else {
180 Log_OC.e(TAG, "Unknown action recieved; ignoring it: " + intent.getAction());
181 }
182
183 return Service.START_STICKY;
184 }
185
186
187 /**
188 * Read from the local database the list of files that must to be kept synchronized and
189 * starts file observers to monitor local changes on them
190 */
191 private void initializeObservedList() {
192 Log_OC.d(TAG, "Loading all kept-in-sync files from database to start watching them");
193
194 //mObserversMap.clear();
195 //mObserverParentsMap.clear();
196
197 Cursor cursorOnKeptInSync = getContentResolver().query(
198 ProviderTableMeta.CONTENT_URI,
199 null,
200 ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
201 new String[] {String.valueOf(1)},
202 null
203 );
204
205 if (cursorOnKeptInSync != null) {
206
207 if (cursorOnKeptInSync.moveToFirst()) {
208
209 String localPath = "";
210 //String remotePath = "";
211 String accountName = "";
212 Account account = null;
213 do {
214 localPath = cursorOnKeptInSync.getString(
215 cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)
216 );
217 accountName = cursorOnKeptInSync.getString(
218 cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER)
219 );
220 /*
221 remotePath = cursorOnKeptInSync.getString(
222 cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_PATH)
223 );
224 */
225
226 account = new Account(accountName, MainApp.getAccountType());
227 if (!AccountUtils.exists(account, this) ||
228 localPath == null || localPath.length() <= 0) {
229 continue;
230 }
231
232 OwnCloudFileObserver observer = mObserversMap.get(localPath);
233 if (observer == null) {
234 observer = new OwnCloudFileObserver(
235 localPath, account, getApplicationContext()
236 );
237 mObserversMap.put(localPath, observer);
238
239 // only if being added
240 if (new File(localPath).exists()) {
241 observer.startWatching();
242 Log_OC.d(TAG, "Started watching file " + localPath);
243 }
244 }
245
246 /*
247 String parentPath = (new File(localPath)).getParent();
248 OwnCloudFileObserver observerParent =
249 new OwnCloudFileObserver( parentPath,
250 account,
251 getApplicationContext());
252 mObserverParentsMap.put(parentPath, observer);
253
254 if (new File(localPath).exists()) {
255 observer.startWatching();
256 Log_OC.d(TAG, "Started watching file " + localPath);
257 observerParent.startWatching();
258 Log_OC.d(TAG, "Started watching parent file " + parentPath);
259 }
260 */
261
262 } while (cursorOnKeptInSync.moveToNext());
263
264 }
265 cursorOnKeptInSync.close();
266 }
267
268 // service does not stopSelf() ; that way it tries to be alive forever
269
270 }
271
272
273 /**
274 * Registers the local copy of a remote file to be observed for local changes,
275 * an automatically updated in the ownCloud server.
276 *
277 * This method does NOT perform a {@link SynchronizeFileOperation} over the file.
278 *
279 * @param file Object representing a remote file which local copy must be observed.
280 * @param account OwnCloud account containing file.
281 */
282 private void addObservedFile(OCFile file, Account account) {
283 Log_OC.v(TAG, "Adding a file to be watched");
284
285 if (file == null) {
286 Log_OC.e(TAG, "Trying to add a NULL file to observer");
287 return;
288 }
289 if (account == null) {
290 Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
291 return;
292 }
293
294 String localPath = file.getStoragePath();
295 if (localPath == null || localPath.length() <= 0) {
296 // file downloading or to be downloaded for the first time
297 localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
298 }
299 OwnCloudFileObserver observer = mObserversMap.get(localPath);
300 if (observer == null) {
301 /// the local file was never registered to observe before
302 observer = new OwnCloudFileObserver( localPath,
303 account,
304 getApplicationContext(),
305 mHandler);
306 mObserversMap.put(localPath, observer);
307 Log_OC.d(TAG, "Observer added for path " + localPath);
308
309 /*
310 String parentPath = (new File(localPath)).getParent();
311 OwnCloudFileObserver observerParent =
312 new OwnCloudFileObserver( parentPath,
313 account,
314 getApplicationContext());
315 mObserverParentsMap.put(parentPath, observer);
316 */
317
318 if (file.isDown()) {
319 observer.startWatching();
320 Log_OC.d(TAG, "Started watching " + localPath);
321 /*observerParent.startWatching();
322 Log_OC.d(TAG, "Started watching parent file " + parentPath);*/
323 }
324 // else - the observance can't be started on a file not already down;
325 // mDownloadReceiver will get noticed when the download of the file finishes
326 }
327
328 }
329
330
331 /**
332 * Unregisters the local copy of a remote file to be observed for local changes.
333 *
334 * Starts to watch it, if the file has a local copy to watch.
335 *
336 * @param file Object representing a remote file which local copy must be not observed longer.
337 * @param account OwnCloud account containing file.
338 */
339 private void removeObservedFile(OCFile file, Account account) {
340 Log_OC.v(TAG, "Removing a file from being watched");
341
342 if (file == null) {
343 Log_OC.e(TAG, "Trying to remove a NULL file");
344 return;
345 }
346 if (account == null) {
347 Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
348 return;
349 }
350
351 String localPath = file.getStoragePath();
352 if (localPath == null || localPath.length() <= 0) {
353 localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
354 }
355
356 OwnCloudFileObserver observer = mObserversMap.get(localPath);
357 if (observer != null) {
358 observer.stopWatching();
359 mObserversMap.remove(observer);
360 Log_OC.d(TAG, "Stopped watching " + localPath);
361
362 } else {
363 Log_OC.d(TAG, "No observer to remove for path " + localPath);
364 }
365
366 }
367
368
369 /**
370 * Private receiver listening to events broadcast by the FileDownloader service.
371 *
372 * Starts and stops the observance on registered files when they are being download,
373 * in order to avoid to start unnecessary synchronizations.
374 */
375 private class DownloadCompletedReceiver extends BroadcastReceiver {
376
377 @Override
378 public void onReceive(Context context, Intent intent) {
379 Log_OC.d(TAG, "Received broadcast intent " + intent);
380
381 String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH);
382 OwnCloudFileObserver observer = mObserversMap.get(downloadPath);
383 if (observer != null) {
384 /*String parentPath = (new File(downloadPath)).getParent();
385 OwnCloudFileObserver observerParent = mObserverParentsMap.get(parentPath); */
386 if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage()) &&
387 new File(downloadPath).exists()) {
388 // no matter is the download was be successful or not; the file could be down,
389 // anyway due to a former download or upload
390 observer.startWatching();
391 Log_OC.d(TAG, "Resuming observance of " + downloadPath);
392 /*observerParent.startWatching();
393 Log_OC.d(TAG, "Watching parent again " + parentPath); */
394
395 } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
396 observer.stopWatching();
397 Log_OC.d(TAG, "Pausing observance of " + downloadPath);
398 }
399
400 } else {
401 Log_OC.d(TAG, "No observer for path " + downloadPath);
402 }
403 }
404
405 }
406
407 }