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