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