FileObserverService.java 14 KB

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