FileObserverService.java 15 KB

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