1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
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.
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.
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/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.util
.HashMap
;
23 import java
.util
.Iterator
;
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
;
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
;
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.
50 * Tries to be alive as long as possible; that is the reason why stopSelf() is never called.
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)}.
57 * @author David A. Velasco
59 public class FileObserverService
extends Service
{
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";
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";
69 private static String TAG
= FileObserverService
.class.getSimpleName();
71 private static Map
<String
, OwnCloudFileObserver
> mObserversMap
;
72 //private static Map<String, OwnCloudFileObserver> mObserverParentsMap;
73 private static DownloadCompletedReceiver mDownloadReceiver
;
77 * Factory method to create intents that allow to start an ACTION_INIT_OBSERVED_LIST command.
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.
83 public static Intent
makeInitIntent(Context context
) {
84 Intent i
= new Intent(context
, FileObserverService
.class);
85 i
.setAction(ACTION_INIT_OBSERVED_LIST
);
91 * Factory method to create intents that allow to start or stop the observance of a file.
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)}.
100 public static Intent
makeObservedFileIntent(
101 Context context
, OCFile file
, Account account
, boolean watchIt
) {
102 Intent intent
= new Intent(context
, FileObserverService
.class);
105 FileObserverService
.CMD_ADD_OBSERVED_FILE
107 FileObserverService
.CMD_DEL_OBSERVED_FILE
109 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, file
);
110 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, account
);
117 public void onCreate() {
118 Log_OC
.d(TAG
, "onCreate");
121 mDownloadReceiver
= new DownloadCompletedReceiver();
122 IntentFilter filter
= new IntentFilter();
123 filter
.addAction(FileDownloader
.getDownloadAddedMessage());
124 filter
.addAction(FileDownloader
.getDownloadFinishMessage());
125 registerReceiver(mDownloadReceiver
, filter
);
127 mObserversMap
= new HashMap
<String
, OwnCloudFileObserver
>();
128 //mObserverParentsMap = new HashMap<String, OwnCloudFileObserver>();
133 public void onDestroy() {
134 Log_OC
.d(TAG
, "onDestroy - FINISHING OBSERVATION");
136 unregisterReceiver(mDownloadReceiver
);
138 Iterator
<OwnCloudFileObserver
> it
= mObserversMap
.values().iterator();
139 while (it
.hasNext()) {
140 it
.next().stopWatching();
142 mObserversMap
.clear();
143 mObserversMap
= null
;
145 //mObserverParentsMap = null;
152 public IBinder
onBind(Intent intent
) {
153 // this service cannot be bound
158 public int onStartCommand(Intent intent
, int flags
, int startId
) {
159 Log_OC
.d(TAG
, "Starting command " + intent
);
161 if (intent
== null
|| ACTION_INIT_OBSERVED_LIST
.equals(intent
.getAction())) {
162 // NULL occurs when system tries to restart the service after its process
164 initializeObservedList();
165 return Service
.START_STICKY
;
167 } else if (CMD_ADD_OBSERVED_FILE
.equals(intent
.getAction())) {
169 (OCFile
)intent
.getParcelableExtra(KEY_CMD_ARG_FILE
),
170 (Account
)intent
.getParcelableExtra(KEY_CMD_ARG_ACCOUNT
)
173 } else if (CMD_DEL_OBSERVED_FILE
.equals(intent
.getAction())) {
175 (OCFile
)intent
.getParcelableExtra(KEY_CMD_ARG_FILE
),
176 (Account
)intent
.getParcelableExtra(KEY_CMD_ARG_ACCOUNT
)
180 Log_OC
.e(TAG
, "Unknown action recieved; ignoring it: " + intent
.getAction());
183 return Service
.START_STICKY
;
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
191 private void initializeObservedList() {
192 Log_OC
.d(TAG
, "Loading all kept-in-sync files from database to start watching them");
194 //mObserversMap.clear();
195 //mObserverParentsMap.clear();
197 Cursor cursorOnKeptInSync
= getContentResolver().query(
198 ProviderTableMeta
.CONTENT_URI
,
200 ProviderTableMeta
.FILE_KEEP_IN_SYNC
+ " = ?",
201 new String
[] {String
.valueOf(1)},
205 if (cursorOnKeptInSync
!= null
) {
207 if (cursorOnKeptInSync
.moveToFirst()) {
209 String localPath
= "";
210 //String remotePath = "";
211 String accountName
= "";
212 Account account
= null
;
214 localPath
= cursorOnKeptInSync
.getString(
215 cursorOnKeptInSync
.getColumnIndex(ProviderTableMeta
.FILE_STORAGE_PATH
)
217 accountName
= cursorOnKeptInSync
.getString(
218 cursorOnKeptInSync
.getColumnIndex(ProviderTableMeta
.FILE_ACCOUNT_OWNER
)
221 remotePath = cursorOnKeptInSync.getString(
222 cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_PATH)
226 account
= new Account(accountName
, MainApp
.getAccountType());
227 if (!AccountUtils
.exists(account
, this) ||
228 localPath
== null
|| localPath
.length() <= 0) {
232 OwnCloudFileObserver observer
= mObserversMap
.get(localPath
);
233 if (observer
== null
) {
234 observer
= new OwnCloudFileObserver(
235 localPath
, account
, getApplicationContext()
237 mObserversMap
.put(localPath
, observer
);
239 // only if being added
240 if (new File(localPath
).exists()) {
241 observer
.startWatching();
242 Log_OC
.d(TAG
, "Started watching file " + localPath
);
247 String parentPath = (new File(localPath)).getParent();
248 OwnCloudFileObserver observerParent =
249 new OwnCloudFileObserver( parentPath,
251 getApplicationContext());
252 mObserverParentsMap.put(parentPath, observer);
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);
262 } while (cursorOnKeptInSync
.moveToNext());
265 cursorOnKeptInSync
.close();
268 // service does not stopSelf() ; that way it tries to be alive forever
274 * Registers the local copy of a remote file to be observed for local changes,
275 * an automatically updated in the ownCloud server.
277 * This method does NOT perform a {@link SynchronizeFileOperation} over the file.
279 * @param file Object representing a remote file which local copy must be observed.
280 * @param account OwnCloud account containing file.
282 private void addObservedFile(OCFile file
, Account account
) {
283 Log_OC
.v(TAG
, "Adding a file to be watched");
286 Log_OC
.e(TAG
, "Trying to add a NULL file to observer");
289 if (account
== null
) {
290 Log_OC
.e(TAG
, "Trying to add a file with a NULL account to observer");
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
);
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
,
304 getApplicationContext(),
306 mObserversMap
.put(localPath
, observer
);
307 Log_OC
.d(TAG
, "Observer added for path " + localPath
);
310 String parentPath = (new File(localPath)).getParent();
311 OwnCloudFileObserver observerParent =
312 new OwnCloudFileObserver( parentPath,
314 getApplicationContext());
315 mObserverParentsMap.put(parentPath, observer);
319 observer
.startWatching();
320 Log_OC
.d(TAG
, "Started watching " + localPath
);
321 /*observerParent.startWatching();
322 Log_OC.d(TAG, "Started watching parent file " + parentPath);*/
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
332 * Unregisters the local copy of a remote file to be observed for local changes.
334 * Starts to watch it, if the file has a local copy to watch.
336 * @param file Object representing a remote file which local copy must be not observed longer.
337 * @param account OwnCloud account containing file.
339 private void removeObservedFile(OCFile file
, Account account
) {
340 Log_OC
.v(TAG
, "Removing a file from being watched");
343 Log_OC
.e(TAG
, "Trying to remove a NULL file");
346 if (account
== null
) {
347 Log_OC
.e(TAG
, "Trying to add a file with a NULL account to observer");
351 String localPath
= file
.getStoragePath();
352 if (localPath
== null
|| localPath
.length() <= 0) {
353 localPath
= FileStorageUtils
.getDefaultSavePathFor(account
.name
, file
);
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
);
363 Log_OC
.d(TAG
, "No observer to remove for path " + localPath
);
370 * Private receiver listening to events broadcast by the FileDownloader service.
372 * Starts and stops the observance on registered files when they are being download,
373 * in order to avoid to start unnecessary synchronizations.
375 private class DownloadCompletedReceiver
extends BroadcastReceiver
{
378 public void onReceive(Context context
, Intent intent
) {
379 Log_OC
.d(TAG
, "Received broadcast intent " + intent
);
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); */
395 } else if (intent
.getAction().equals(FileDownloader
.getDownloadAddedMessage())) {
396 observer
.stopWatching();
397 Log_OC
.d(TAG
, "Pausing observance of " + downloadPath
);
401 Log_OC
.d(TAG
, "No observer for path " + downloadPath
);