FileObserverService.java 11 KB

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