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