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 as published by
  7. * the Free Software Foundation, either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package com.owncloud.android.files.services;
  20. import java.io.File;
  21. import java.util.HashMap;
  22. import java.util.Map;
  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 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. import android.util.Log;
  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.DOWNLOAD_ADDED_MESSAGE);
  62. filter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
  63. registerReceiver(mDownloadReceiver, filter);
  64. mObserversMap = new HashMap<String, OwnCloudFileObserver>();
  65. //initializeObservedList();
  66. }
  67. @Override
  68. public void onDestroy() {
  69. super.onDestroy();
  70. unregisterReceiver(mDownloadReceiver);
  71. mObserversMap = null; // TODO study carefully the life cycle of Services to grant the best possible observance
  72. Log.d(TAG, "Bye, bye");
  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.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.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.getAccounts();
  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. OwnCloudFileObserver.CHANGES_ONLY);
  142. mObserversMap.put(path, observer);
  143. if (new File(path).exists()) {
  144. observer.startWatching();
  145. Log.d(TAG, "Started watching file " + path);
  146. }
  147. } while (c.moveToNext());
  148. c.close();
  149. }
  150. /**
  151. * Registers the local copy of a remote file to be observed for local changes,
  152. * an automatically updated in the ownCloud server.
  153. *
  154. * This method does NOT perform a {@link SynchronizeFileOperation} over the file.
  155. *
  156. * TODO We are ignoring that, currently, a local file can be linked to different files
  157. * in ownCloud if it's uploaded several times. That's something pending to update: we
  158. * will avoid that the same local file is linked to different remote files.
  159. *
  160. * @param file Object representing a remote file which local copy must be observed.
  161. * @param account OwnCloud account containing file.
  162. */
  163. private void addObservedFile(OCFile file, Account account) {
  164. if (file == null) {
  165. Log.e(TAG, "Trying to add a NULL file to observer");
  166. return;
  167. }
  168. String localPath = file.getStoragePath();
  169. if (localPath == null || localPath.length() <= 0) { // file downloading / to be download for the first time
  170. localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
  171. }
  172. OwnCloudFileObserver observer = mObserversMap.get(localPath);
  173. if (observer == null) {
  174. /// the local file was never registered to observe before
  175. observer = new OwnCloudFileObserver( localPath,
  176. account,
  177. getApplicationContext(),
  178. OwnCloudFileObserver.CHANGES_ONLY);
  179. mObserversMap.put(localPath, observer);
  180. Log.d(TAG, "Observer added for path " + localPath);
  181. if (file.isDown()) {
  182. observer.startWatching();
  183. Log.d(TAG, "Started watching " + localPath);
  184. } // else - the observance can't be started on a file not already down; mDownloadReceiver will get noticed when the download of the file finishes
  185. }
  186. }
  187. /**
  188. * Unregisters the local copy of a remote file to be observed for local changes.
  189. *
  190. * Starts to watch it, if the file has a local copy to watch.
  191. *
  192. * TODO We are ignoring that, currently, a local file can be linked to different files
  193. * in ownCloud if it's uploaded several times. That's something pending to update: we
  194. * will avoid that the same local file is linked to different remote files.
  195. *
  196. * @param file Object representing a remote file which local copy must be not observed longer.
  197. * @param account OwnCloud account containing file.
  198. */
  199. private void removeObservedFile(OCFile file, Account account) {
  200. if (file == null) {
  201. Log.e(TAG, "Trying to remove a NULL file");
  202. return;
  203. }
  204. String localPath = file.getStoragePath();
  205. if (localPath == null || localPath.length() <= 0) {
  206. localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
  207. }
  208. OwnCloudFileObserver observer = mObserversMap.get(localPath);
  209. if (observer != null) {
  210. observer.stopWatching();
  211. mObserversMap.remove(observer);
  212. Log.d(TAG, "Stopped watching " + localPath);
  213. }
  214. }
  215. /**
  216. * Private receiver listening to events broadcast by the FileDownloader service.
  217. *
  218. * Starts and stops the observance on registered files when they are being download,
  219. * in order to avoid to start unnecessary synchronizations.
  220. */
  221. private class DownloadCompletedReceiverBis extends BroadcastReceiver {
  222. @Override
  223. public void onReceive(Context context, Intent intent) {
  224. String downloadPath = intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH);
  225. OwnCloudFileObserver observer = mObserversMap.get(downloadPath);
  226. if (observer != null) {
  227. if (intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE) &&
  228. new File(downloadPath).exists()) { // the download could be successful, or not; in both cases, the file could be down, due to a former download or upload
  229. observer.startWatching();
  230. Log.d(TAG, "Watching again " + downloadPath);
  231. } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
  232. observer.stopWatching();
  233. Log.d(TAG, "Disabling observance of " + downloadPath);
  234. }
  235. }
  236. }
  237. }
  238. }