FileObserverService.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. * Copyright (C) 2012-2014 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. package com.owncloud.android.services.observer;
  19. import java.io.File;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.Map;
  23. import android.accounts.Account;
  24. import android.app.Service;
  25. import android.content.BroadcastReceiver;
  26. import android.content.Context;
  27. import android.content.Intent;
  28. import android.content.IntentFilter;
  29. import android.database.Cursor;
  30. import android.os.IBinder;
  31. import com.owncloud.android.MainApp;
  32. import com.owncloud.android.authentication.AccountUtils;
  33. import com.owncloud.android.datamodel.OCFile;
  34. import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
  35. import com.owncloud.android.files.services.FileDownloader;
  36. import com.owncloud.android.operations.SynchronizeFileOperation;
  37. import com.owncloud.android.utils.FileStorageUtils;
  38. import com.owncloud.android.utils.Log_OC;
  39. /**
  40. * Service keeping a list of {@link FolderObserver} instances that watch for local
  41. * changes in favorite files (formerly known as kept-in-sync files) and try to
  42. * synchronize them with the OC server as soon as possible.
  43. *
  44. * Tries to be alive as long as possible; that is the reason why stopSelf() is
  45. * never called.
  46. *
  47. * It is expected that the system eventually kills the service when runs low of
  48. * memory. To minimize the impact of this, the service always returns
  49. * Service.START_STICKY, and the later restart of the service is explicitly
  50. * considered in {@link FileObserverService#onStartCommand(Intent, int, int)}.
  51. *
  52. * @author David A. Velasco
  53. */
  54. public class FileObserverService extends Service {
  55. public final static String MY_NAME = FileObserverService.class.getCanonicalName();
  56. public final static String ACTION_START_OBSERVE = MY_NAME + ".action.START_OBSERVATION";
  57. public final static String ACTION_ADD_OBSERVED_FILE = MY_NAME + ".action.ADD_OBSERVED_FILE";
  58. public final static String ACTION_DEL_OBSERVED_FILE = MY_NAME + ".action.DEL_OBSERVED_FILE";
  59. private final static String ARG_FILE = "ARG_FILE";
  60. private final static String ARG_ACCOUNT = "ARG_ACCOUNT";
  61. private static String TAG = FileObserverService.class.getSimpleName();
  62. private Map<String, FolderObserver> mFolderObserversMap;
  63. private DownloadCompletedReceiver mDownloadReceiver;
  64. /**
  65. * Factory method to create intents that allow to start an ACTION_START_OBSERVE command.
  66. *
  67. * @param context Android context of the caller component.
  68. * @return Intent that starts a command ACTION_START_OBSERVE when
  69. * {@link Context#startService(Intent)} is called.
  70. */
  71. public static Intent makeInitIntent(Context context) {
  72. Intent i = new Intent(context, FileObserverService.class);
  73. i.setAction(ACTION_START_OBSERVE);
  74. return i;
  75. }
  76. /**
  77. * Factory method to create intents that allow to start or stop the
  78. * observance of a file.
  79. *
  80. * @param context Android context of the caller component.
  81. * @param file OCFile to start or stop to watch.
  82. * @param account OC account containing file.
  83. * @param watchIt 'True' creates an intent to watch, 'false' an intent to stop watching.
  84. * @return Intent to start or stop the observance of a file through a call
  85. * to {@link Context#startService(Intent)}.
  86. */
  87. public static Intent makeObservedFileIntent(
  88. Context context, OCFile file, Account account, boolean watchIt) {
  89. Intent intent = new Intent(context, FileObserverService.class);
  90. intent.setAction(watchIt ? FileObserverService.ACTION_ADD_OBSERVED_FILE
  91. : FileObserverService.ACTION_DEL_OBSERVED_FILE);
  92. intent.putExtra(FileObserverService.ARG_FILE, file);
  93. intent.putExtra(FileObserverService.ARG_ACCOUNT, account);
  94. return intent;
  95. }
  96. /**
  97. * Initialize the service.
  98. */
  99. @Override
  100. public void onCreate() {
  101. Log_OC.d(TAG, "onCreate");
  102. super.onCreate();
  103. mDownloadReceiver = new DownloadCompletedReceiver();
  104. IntentFilter filter = new IntentFilter();
  105. filter.addAction(FileDownloader.getDownloadAddedMessage());
  106. filter.addAction(FileDownloader.getDownloadFinishMessage());
  107. registerReceiver(mDownloadReceiver, filter);
  108. mFolderObserversMap = new HashMap<String, FolderObserver>();
  109. }
  110. /**
  111. * Release resources.
  112. */
  113. @Override
  114. public void onDestroy() {
  115. Log_OC.d(TAG, "onDestroy - finishing observation of favorite files");
  116. unregisterReceiver(mDownloadReceiver);
  117. Iterator<FolderObserver> itOCFolder = mFolderObserversMap.values().iterator();
  118. while (itOCFolder.hasNext()) {
  119. itOCFolder.next().stopWatching();
  120. }
  121. mFolderObserversMap.clear();
  122. mFolderObserversMap = null;
  123. super.onDestroy();
  124. }
  125. /**
  126. * This service cannot be bound.
  127. */
  128. @Override
  129. public IBinder onBind(Intent intent) {
  130. return null;
  131. }
  132. /**
  133. * Handles requests to:
  134. * - (re)start watching (ACTION_START_OBSERVE)
  135. * - add an {@link OCFile} to be watched (ATION_ADD_OBSERVED_FILE)
  136. * - stop observing an {@link OCFile} (ACTION_DEL_OBSERVED_FILE)
  137. */
  138. @Override
  139. public int onStartCommand(Intent intent, int flags, int startId) {
  140. Log_OC.d(TAG, "Starting command " + intent);
  141. if (intent == null || ACTION_START_OBSERVE.equals(intent.getAction())) {
  142. // NULL occurs when system tries to restart the service after its
  143. // process was killed
  144. startObservation();
  145. return Service.START_STICKY;
  146. } else if (ACTION_ADD_OBSERVED_FILE.equals(intent.getAction())) {
  147. OCFile file = (OCFile) intent.getParcelableExtra(ARG_FILE);
  148. Account account = (Account) intent.getParcelableExtra(ARG_ACCOUNT);
  149. addObservedFile(file, account);
  150. } else if (ACTION_DEL_OBSERVED_FILE.equals(intent.getAction())) {
  151. removeObservedFile((OCFile) intent.getParcelableExtra(ARG_FILE),
  152. (Account) intent.getParcelableExtra(ARG_ACCOUNT));
  153. } else {
  154. Log_OC.e(TAG, "Unknown action recieved; ignoring it: " + intent.getAction());
  155. }
  156. return Service.START_STICKY;
  157. }
  158. /**
  159. * Read from the local database the list of files that must to be kept
  160. * synchronized and starts observers to monitor local changes on them.
  161. *
  162. * Updates the list of currently observed files if called multiple times.
  163. */
  164. private void startObservation() {
  165. Log_OC.d(TAG, "Loading all kept-in-sync files from database to start watching them");
  166. // query for any favorite file in any OC account
  167. Cursor cursorOnKeptInSync = getContentResolver().query(
  168. ProviderTableMeta.CONTENT_URI,
  169. null,
  170. ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
  171. new String[] { String.valueOf(1) },
  172. null
  173. );
  174. if (cursorOnKeptInSync != null) {
  175. if (cursorOnKeptInSync.moveToFirst()) {
  176. String localPath = "";
  177. String accountName = "";
  178. Account account = null;
  179. do {
  180. localPath = cursorOnKeptInSync.getString(cursorOnKeptInSync
  181. .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
  182. accountName = cursorOnKeptInSync.getString(cursorOnKeptInSync
  183. .getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER));
  184. account = new Account(accountName, MainApp.getAccountType());
  185. if (!AccountUtils.exists(account, this) || localPath == null || localPath.length() <= 0) {
  186. continue;
  187. }
  188. addObservedFile(localPath, account);
  189. } while (cursorOnKeptInSync.moveToNext());
  190. }
  191. cursorOnKeptInSync.close();
  192. }
  193. // service does not stopSelf() ; that way it tries to be alive forever
  194. }
  195. /**
  196. * Registers the local copy of a remote file to be observed for local
  197. * changes, an automatically updated in the ownCloud server.
  198. *
  199. * This method does NOT perform a {@link SynchronizeFileOperation} over the
  200. * file.
  201. *
  202. * @param file Object representing a remote file which local copy must be observed.
  203. * @param account OwnCloud account containing file.
  204. */
  205. private void addObservedFile(OCFile file, Account account) {
  206. Log_OC.v(TAG, "Adding a file to be watched");
  207. if (file == null) {
  208. Log_OC.e(TAG, "Trying to add a NULL file to observer");
  209. return;
  210. }
  211. if (account == null) {
  212. Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
  213. return;
  214. }
  215. String localPath = file.getStoragePath();
  216. if (localPath == null || localPath.length() <= 0) {
  217. // file downloading or to be downloaded for the first time
  218. localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
  219. }
  220. addObservedFile(localPath, account);
  221. }
  222. /**
  223. * Registers a local file to be observed for changes.
  224. *
  225. * @param localPath Absolute path in the local file system to the file to be observed.
  226. * @param account OwnCloud account associated to the local file.
  227. */
  228. private void addObservedFile(String localPath, Account account) {
  229. File file = new File(localPath);
  230. String parentPath = file.getParent();
  231. FolderObserver observer = mFolderObserversMap.get(parentPath);
  232. if (observer == null) {
  233. observer = new FolderObserver(parentPath, account, getApplicationContext());
  234. mFolderObserversMap.put(parentPath, observer);
  235. Log_OC.d(TAG, "Observer added for parent folder " + parentPath + "/");
  236. }
  237. observer.startWatching(file.getName());
  238. Log_OC.d(TAG, "Added " + localPath + " to list of observed children");
  239. }
  240. /**
  241. * Unregisters the local copy of a remote file to be observed for local changes.
  242. *
  243. * @param file Object representing a remote file which local copy must be not
  244. * observed longer.
  245. * @param account OwnCloud account containing file.
  246. */
  247. private void removeObservedFile(OCFile file, Account account) {
  248. Log_OC.v(TAG, "Removing a file from being watched");
  249. if (file == null) {
  250. Log_OC.e(TAG, "Trying to remove a NULL file");
  251. return;
  252. }
  253. if (account == null) {
  254. Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
  255. return;
  256. }
  257. String localPath = file.getStoragePath();
  258. if (localPath == null || localPath.length() <= 0) {
  259. localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
  260. }
  261. removeObservedFile(localPath);
  262. }
  263. /**
  264. * Unregisters a local file from being observed for changes.
  265. *
  266. * @param localPath Absolute path in the local file system to the target file.
  267. */
  268. private void removeObservedFile(String localPath) {
  269. File file = new File(localPath);
  270. String parentPath = file.getParent();
  271. FolderObserver observer = mFolderObserversMap.get(parentPath);
  272. if (observer != null) {
  273. observer.stopWatching(file.getName());
  274. if (observer.isEmpty()) {
  275. mFolderObserversMap.remove(parentPath);
  276. Log_OC.d(TAG, "Observer removed for parent folder " + parentPath + "/");
  277. }
  278. } else {
  279. Log_OC.d(TAG, "No observer to remove for path " + localPath);
  280. }
  281. }
  282. /**
  283. * Private receiver listening to events broadcasted by the {@link FileDownloader} service.
  284. *
  285. * Pauses and resumes the observance on registered files while being download,
  286. * in order to avoid to unnecessary synchronizations.
  287. */
  288. private class DownloadCompletedReceiver extends BroadcastReceiver {
  289. @Override
  290. public void onReceive(Context context, Intent intent) {
  291. Log_OC.d(TAG, "Received broadcast intent " + intent);
  292. File downloadedFile = new File(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
  293. String parentPath = downloadedFile.getParent();
  294. FolderObserver observer = mFolderObserversMap.get(parentPath);
  295. if (observer != null) {
  296. if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage())
  297. && downloadedFile.exists()) {
  298. // no matter if the download was successful or not; the
  299. // file could be down anyway due to a former download or upload
  300. observer.startWatching(downloadedFile.getName());
  301. Log_OC.d(TAG, "Resuming observance of " + downloadedFile.getAbsolutePath());
  302. } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
  303. observer.stopWatching(downloadedFile.getName());
  304. Log_OC.d(TAG, "Pausing observance of " + downloadedFile.getAbsolutePath());
  305. }
  306. } else {
  307. Log_OC.d(TAG, "No observer for path " + downloadedFile.getAbsolutePath());
  308. }
  309. }
  310. }
  311. }