Removed some unused classes
[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 as published by
7 * the Free Software Foundation, either version 3 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
20 package com.owncloud.android.files.services;
21
22 import java.io.File;
23 import java.util.HashMap;
24 import java.util.Map;
25
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 import android.util.Log;
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 public class LocalBinder extends Binder {
62 FileObserverService getService() {
63 return FileObserverService.this;
64 }
65 }
66
67 @Override
68 public void onCreate() {
69 super.onCreate();
70 mDownloadReceiver = new DownloadCompletedReceiverBis();
71 IntentFilter filter = new IntentFilter();
72 filter.addAction(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
73 filter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
74 registerReceiver(mDownloadReceiver, filter);
75
76 mObserversMap = new HashMap<String, OwnCloudFileObserver>();
77 //initializeObservedList();
78 }
79
80
81 @Override
82 public void onDestroy() {
83 super.onDestroy();
84 unregisterReceiver(mDownloadReceiver);
85 mObserversMap = null; // TODO study carefully the life cycle of Services to grant the best possible observance
86 Log.d(TAG, "Bye, bye");
87 }
88
89
90 @Override
91 public IBinder onBind(Intent intent) {
92 return mBinder;
93 }
94
95 @Override
96 public int onStartCommand(Intent intent, int flags, int startId) {
97 // this occurs when system tries to restart
98 // service, so we need to reinitialize observers
99 if (intent == null) {
100 initializeObservedList();
101 return Service.START_STICKY;
102 }
103
104 if (!intent.hasExtra(KEY_FILE_CMD)) {
105 Log.e(TAG, "No KEY_FILE_CMD argument given");
106 return Service.START_STICKY;
107 }
108
109 switch (intent.getIntExtra(KEY_FILE_CMD, -1)) {
110 case CMD_INIT_OBSERVED_LIST:
111 initializeObservedList();
112 break;
113 case CMD_ADD_OBSERVED_FILE:
114 addObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
115 (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
116 break;
117 case CMD_DEL_OBSERVED_FILE:
118 removeObservedFile( (OCFile)intent.getParcelableExtra(KEY_CMD_ARG_FILE),
119 (Account)intent.getParcelableExtra(KEY_CMD_ARG_ACCOUNT));
120 break;
121 default:
122 Log.wtf(TAG, "Incorrect key given");
123 }
124
125 return Service.START_STICKY;
126 }
127
128
129 /**
130 * Read from the local database the list of files that must to be kept synchronized and
131 * starts file observers to monitor local changes on them
132 */
133 private void initializeObservedList() {
134 mObserversMap.clear();
135 Cursor c = getContentResolver().query(
136 ProviderTableMeta.CONTENT_URI,
137 null,
138 ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
139 new String[] {String.valueOf(1)},
140 null);
141 if (c == null || !c.moveToFirst()) return;
142 AccountManager acm = AccountManager.get(this);
143 Account[] accounts = acm.getAccounts();
144 do {
145 Account account = null;
146 for (Account a : accounts)
147 if (a.name.equals(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER)))) {
148 account = a;
149 break;
150 }
151
152 if (account == null) continue;
153 FileDataStorageManager storage =
154 new FileDataStorageManager(account, getContentResolver());
155 if (!storage.fileExists(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH))))
156 continue;
157
158 String path = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
159 if (path == null || path.length() <= 0)
160 continue;
161 OwnCloudFileObserver observer =
162 new OwnCloudFileObserver( path,
163 account,
164 getApplicationContext(),
165 OwnCloudFileObserver.CHANGES_ONLY);
166 mObserversMap.put(path, observer);
167 if (new File(path).exists()) {
168 observer.startWatching();
169 Log.d(TAG, "Started watching file " + path);
170 }
171
172 } while (c.moveToNext());
173 c.close();
174 }
175
176
177 /**
178 * Registers the local copy of a remote file to be observed for local changes,
179 * an automatically updated in the ownCloud server.
180 *
181 * This method does NOT perform a {@link SynchronizeFileOperation} over the file.
182 *
183 * TODO We are ignoring that, currently, a local file can be linked to different files
184 * in ownCloud if it's uploaded several times. That's something pending to update: we
185 * will avoid that the same local file is linked to different remote files.
186 *
187 * @param file Object representing a remote file which local copy must be observed.
188 * @param account OwnCloud account containing file.
189 */
190 private void addObservedFile(OCFile file, Account account) {
191 if (file == null) {
192 Log.e(TAG, "Trying to add a NULL file to observer");
193 return;
194 }
195 String localPath = file.getStoragePath();
196 if (localPath == null || localPath.length() <= 0) { // file downloading / to be download for the first time
197 localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
198 }
199 OwnCloudFileObserver observer = mObserversMap.get(localPath);
200 if (observer == null) {
201 /// the local file was never registered to observe before
202 observer = new OwnCloudFileObserver( localPath,
203 account,
204 getApplicationContext(),
205 OwnCloudFileObserver.CHANGES_ONLY);
206 mObserversMap.put(localPath, observer);
207 Log.d(TAG, "Observer added for path " + localPath);
208
209 if (file.isDown()) {
210 observer.startWatching();
211 Log.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.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.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.DOWNLOAD_FINISH_MESSAGE) &&
264 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
265 observer.startWatching();
266 Log.d(TAG, "Watching again " + downloadPath);
267
268 } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
269 observer.stopWatching();
270 Log.d(TAG, "Disabling observance of " + downloadPath);
271 }
272 }
273 }
274
275 }
276
277 }