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