FileObserverService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. package com.owncloud.android.files.services;
  19. import java.io.File;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22. import com.owncloud.android.datamodel.FileDataStorageManager;
  23. import com.owncloud.android.datamodel.OCFile;
  24. import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
  25. import com.owncloud.android.files.OwnCloudFileObserver;
  26. import com.owncloud.android.operations.SynchronizeFileOperation;
  27. import com.owncloud.android.utils.FileStorageUtils;
  28. import com.owncloud.android.utils.Log_OC;
  29. import android.accounts.Account;
  30. import android.accounts.AccountManager;
  31. import android.app.Service;
  32. import android.content.BroadcastReceiver;
  33. import android.content.Context;
  34. import android.content.Intent;
  35. import android.content.IntentFilter;
  36. import android.database.Cursor;
  37. import android.os.Binder;
  38. import android.os.IBinder;
  39. public class FileObserverService extends Service {
  40. public final static int CMD_INIT_OBSERVED_LIST = 1;
  41. public final static int CMD_ADD_OBSERVED_FILE = 2;
  42. public final static int CMD_DEL_OBSERVED_FILE = 3;
  43. public final static String KEY_FILE_CMD = "KEY_FILE_CMD";
  44. public final static String KEY_CMD_ARG_FILE = "KEY_CMD_ARG_FILE";
  45. public final static String KEY_CMD_ARG_ACCOUNT = "KEY_CMD_ARG_ACCOUNT";
  46. private static String TAG = FileObserverService.class.getSimpleName();
  47. private static Map<String, OwnCloudFileObserver> mObserversMap;
  48. private static DownloadCompletedReceiverBis mDownloadReceiver;
  49. private IBinder mBinder = new LocalBinder();
  50. public class LocalBinder extends Binder {
  51. FileObserverService getService() {
  52. return FileObserverService.this;
  53. }
  54. }
  55. @Override
  56. public void onCreate() {
  57. super.onCreate();
  58. mDownloadReceiver = new DownloadCompletedReceiverBis();
  59. IntentFilter filter = new IntentFilter();
  60. filter.addAction(FileDownloader.getDownloadAddedMessage());
  61. filter.addAction(FileDownloader.getDownloadFinishMessage());
  62. registerReceiver(mDownloadReceiver, filter);
  63. mObserversMap = new HashMap<String, OwnCloudFileObserver>();
  64. //initializeObservedList();
  65. }
  66. @Override
  67. public void onDestroy() {
  68. super.onDestroy();
  69. unregisterReceiver(mDownloadReceiver);
  70. mObserversMap = null; // TODO study carefully the life cycle of Services to grant the best possible observance
  71. Log_OC.d(TAG, "Bye, bye");
  72. }
  73. @Override
  74. public IBinder onBind(Intent intent) {
  75. return mBinder;
  76. }
  77. @Override
  78. public int onStartCommand(Intent intent, int flags, int startId) {
  79. // this occurs when system tries to restart
  80. // service, so we need to reinitialize observers
  81. if (intent == null) {
  82. initializeObservedList();
  83. return Service.START_STICKY;
  84. }
  85. if (!intent.hasExtra(KEY_FILE_CMD)) {
  86. Log_OC.e(TAG, "No KEY_FILE_CMD argument given");
  87. return Service.START_STICKY;
  88. }
  89. switch (intent.getIntExtra(KEY_FILE_CMD, -1)) {
  90. case CMD_INIT_OBSERVED_LIST:
  91. initializeObservedList();
  92. break;
  93. case CMD_ADD_OBSERVED_FILE:
  94. addObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
  95. (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
  96. break;
  97. case CMD_DEL_OBSERVED_FILE:
  98. removeObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
  99. (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
  100. break;
  101. default:
  102. Log_OC.wtf(TAG, "Incorrect key given");
  103. }
  104. return Service.START_STICKY;
  105. }
  106. /**
  107. * Read from the local database the list of files that must to be kept synchronized and
  108. * starts file observers to monitor local changes on them
  109. */
  110. private void initializeObservedList() {
  111. mObserversMap.clear();
  112. Cursor c = getContentResolver().query(
  113. ProviderTableMeta.CONTENT_URI,
  114. null,
  115. ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
  116. new String[] {String.valueOf(1)},
  117. null);
  118. if (c == null || !c.moveToFirst()) return;
  119. AccountManager acm = AccountManager.get(this);
  120. Account[] accounts = acm.getAccounts();
  121. do {
  122. Account account = null;
  123. for (Account a : accounts)
  124. if (a.name.equals(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER)))) {
  125. account = a;
  126. break;
  127. }
  128. if (account == null) continue;
  129. FileDataStorageManager storage =
  130. new FileDataStorageManager(account, getContentResolver());
  131. if (!storage.fileExists(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))))
  132. continue;
  133. String path = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
  134. if (path == null || path.length() <= 0)
  135. continue;
  136. OwnCloudFileObserver observer =
  137. new OwnCloudFileObserver( path,
  138. account,
  139. getApplicationContext(),
  140. OwnCloudFileObserver.CHANGES_ONLY);
  141. mObserversMap.put(path, observer);
  142. if (new File(path).exists()) {
  143. observer.startWatching();
  144. Log_OC.d(TAG, "Started watching file " + path);
  145. }
  146. } while (c.moveToNext());
  147. c.close();
  148. }
  149. /**
  150. * Registers the local copy of a remote file to be observed for local changes,
  151. * an automatically updated in the ownCloud server.
  152. *
  153. * This method does NOT perform a {@link SynchronizeFileOperation} over the file.
  154. *
  155. * TODO We are ignoring that, currently, a local file can be linked to different files
  156. * in ownCloud if it's uploaded several times. That's something pending to update: we
  157. * will avoid that the same local file is linked to different remote files.
  158. *
  159. * @param file Object representing a remote file which local copy must be observed.
  160. * @param account OwnCloud account containing file.
  161. */
  162. private void addObservedFile(OCFile file, Account account) {
  163. if (file == null) {
  164. Log_OC.e(TAG, "Trying to add a NULL file to observer");
  165. return;
  166. }
  167. String localPath = file.getStoragePath();
  168. if (localPath == null || localPath.length() <= 0) { // file downloading / to be download for the first time
  169. localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
  170. }
  171. OwnCloudFileObserver observer = mObserversMap.get(localPath);
  172. if (observer == null) {
  173. /// the local file was never registered to observe before
  174. observer = new OwnCloudFileObserver( localPath,
  175. account,
  176. getApplicationContext(),
  177. OwnCloudFileObserver.CHANGES_ONLY);
  178. mObserversMap.put(localPath, observer);
  179. Log_OC.d(TAG, "Observer added for path " + localPath);
  180. if (file.isDown()) {
  181. observer.startWatching();
  182. Log_OC.d(TAG, "Started watching " + localPath);
  183. } // else - the observance can't be started on a file not already down; mDownloadReceiver will get noticed when the download of the file finishes
  184. }
  185. }
  186. /**
  187. * Unregisters the local copy of a remote file to be observed for local changes.
  188. *
  189. * Starts to watch it, if the file has a local copy to watch.
  190. *
  191. * TODO We are ignoring that, currently, a local file can be linked to different files
  192. * in ownCloud if it's uploaded several times. That's something pending to update: we
  193. * will avoid that the same local file is linked to different remote files.
  194. *
  195. * @param file Object representing a remote file which local copy must be not observed longer.
  196. * @param account OwnCloud account containing file.
  197. */
  198. private void removeObservedFile(OCFile file, Account account) {
  199. if (file == null) {
  200. Log_OC.e(TAG, "Trying to remove a NULL file");
  201. return;
  202. }
  203. String localPath = file.getStoragePath();
  204. if (localPath == null || localPath.length() <= 0) {
  205. localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
  206. }
  207. OwnCloudFileObserver observer = mObserversMap.get(localPath);
  208. if (observer != null) {
  209. observer.stopWatching();
  210. mObserversMap.remove(observer);
  211. Log_OC.d(TAG, "Stopped watching " + localPath);
  212. }
  213. }
  214. /**
  215. * Private receiver listening to events broadcast by the FileDownloader service.
  216. *
  217. * Starts and stops the observance on registered files when they are being download,
  218. * in order to avoid to start unnecessary synchronizations.
  219. */
  220. private class DownloadCompletedReceiverBis extends BroadcastReceiver {
  221. @Override
  222. public void onReceive(Context context, Intent intent) {
  223. String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH);
  224. OwnCloudFileObserver observer = mObserversMap.get(downloadPath);
  225. if (observer != null) {
  226. if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage()) &&
  227. new File(downloadPath).exists()) { // the download could be successful. not; in both cases, the file could be down, due to a former download or upload
  228. observer.startWatching();
  229. Log_OC.d(TAG, "Watching again " + downloadPath);
  230. } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
  231. observer.stopWatching();
  232. Log_OC.d(TAG, "Disabling observance of " + downloadPath);
  233. }
  234. }
  235. }
  236. }
  237. }