Updating synchronization for providing SSL warning when necessary; STEP 2: added...
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 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.syncadapter;
20
21 import java.io.IOException;
22 import java.util.List;
23
24 import org.apache.jackrabbit.webdav.DavException;
25 import org.json.JSONObject;
26
27 import com.owncloud.android.AccountUtils;
28 import com.owncloud.android.R;
29 import com.owncloud.android.authenticator.AccountAuthenticator;
30 import com.owncloud.android.datamodel.DataStorageManager;
31 import com.owncloud.android.datamodel.FileDataStorageManager;
32 import com.owncloud.android.datamodel.OCFile;
33 import com.owncloud.android.operations.RemoteOperationResult;
34 import com.owncloud.android.operations.SynchronizeFolderOperation;
35 import com.owncloud.android.utils.OwnCloudVersion;
36
37 import android.accounts.Account;
38 import android.app.Notification;
39 import android.app.NotificationManager;
40 import android.app.PendingIntent;
41 import android.content.ContentProviderClient;
42 import android.content.ContentResolver;
43 import android.content.Context;
44 import android.content.Intent;
45 import android.content.SyncResult;
46 import android.os.Bundle;
47 import android.util.Log;
48 import eu.alefzero.webdav.WebdavClient;
49
50 /**
51 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
52 * platform ContactOperations provider.
53 *
54 * @author Bartek Przybylski
55 */
56 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
57
58 private final static String TAG = "FileSyncAdapter";
59
60 /**
61 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
62 */
63 private static final int MAX_FAILED_RESULTS = 3;
64
65 private long mCurrentSyncTime;
66 private boolean mCancellation;
67 private boolean mIsManualSync;
68 private int mFailedResultsCounter;
69 private RemoteOperationResult mLastFailedResult;
70
71 public FileSyncAdapter(Context context, boolean autoInitialize) {
72 super(context, autoInitialize);
73 }
74
75 @Override
76 public synchronized void onPerformSync(Account account, Bundle extras,
77 String authority, ContentProviderClient provider,
78 SyncResult syncResult) {
79
80 mCancellation = false;
81 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
82 mFailedResultsCounter = 0;
83 mLastFailedResult = null;
84
85 this.setAccount(account);
86 this.setContentProvider(provider);
87 this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
88
89 Log.d(TAG, "syncing owncloud account " + account.name);
90
91 sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI
92
93 try {
94 updateOCVersion();
95 mCurrentSyncTime = System.currentTimeMillis();
96 if (!mCancellation) {
97 fetchData(OCFile.PATH_SEPARATOR, syncResult, DataStorageManager.ROOT_PARENT_ID);
98
99 } else {
100 Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");
101 }
102
103 } finally {
104 // it's important making this although very unexpected errors occur; that's the reason for the finally
105
106 if (mFailedResultsCounter > 0 && mIsManualSync) {
107 /// don't let the system synchronization manager retries MANUAL synchronizations
108 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
109 syncResult.tooManyRetries = true;
110
111 /// notify the user about the failure of MANUAL synchronization
112 notifyFailedSynchronization();
113 }
114 sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI
115 }
116
117 }
118
119
120
121 /**
122 * Called by system SyncManager when a synchronization is required to be cancelled.
123 *
124 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
125 * fetched will be still saved in the database. See onPerformSync implementation.
126 */
127 @Override
128 public void onSyncCanceled() {
129 Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
130 mCancellation = true;
131 super.onSyncCanceled();
132 }
133
134
135 /**
136 * Updates the locally stored version value of the ownCloud server
137 */
138 private void updateOCVersion() {
139 String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);
140 statUrl += AccountUtils.STATUS_PATH;
141
142 try {
143 String result = getClient().getResultAsString(statUrl);
144 if (result != null) {
145 try {
146 JSONObject json = new JSONObject(result);
147 if (json != null && json.getString("version") != null) {
148 OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));
149 if (ocver.isVersionValid()) {
150 getAccountManager().setUserData(getAccount(), AccountAuthenticator.KEY_OC_VERSION, ocver.toString());
151 Log.d(TAG, "Got new OC version " + ocver.toString());
152 } else {
153 Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));
154 }
155 }
156 } catch (Throwable e) {
157 Log.w(TAG, "Couldn't parse version response", e);
158 }
159 } else {
160 Log.w(TAG, "Problem while getting ocversion from server");
161 }
162 } catch (Exception e) {
163 Log.e(TAG, "Problem getting response from server", e);
164 }
165 }
166
167
168
169 /**
170 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
171 *
172 * @param remotePath Remote path to the folder to synchronize.
173 * @param parentId Database Id of the folder to synchronize.
174 * @param syncResult Object to update for communicate results to the system's synchronization manager.
175 */
176 private void fetchData(String remotePath, SyncResult syncResult, long parentId) {
177
178 if (mFailedResultsCounter > MAX_FAILED_RESULTS && isFinisher(mLastFailedResult))
179 return;
180
181 // get client object to connect to the remote ownCloud server
182 WebdavClient client = null;
183 try {
184 client = getClient();
185 } catch (IOException e) {
186 syncResult.stats.numIoExceptions++;
187 Log.d(TAG, "Could not get client object while trying to synchronize - impossible to continue");
188 return;
189 }
190
191 // perform folder synchronization
192 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath,
193 mCurrentSyncTime,
194 parentId,
195 getStorageManager(),
196 getAccount(),
197 getContext()
198 );
199 RemoteOperationResult result = synchFolderOp.execute(client);
200
201
202 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
203 sendStickyBroadcast(true, remotePath, null);
204
205 if (result.isSuccess()) {
206 // synchronize children folders
207 List<OCFile> children = synchFolderOp.getChildren();
208 fetchChildren(children, syncResult); // beware of the 'hidden' recursion here!
209
210 } else {
211 if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
212 syncResult.stats.numAuthExceptions++;
213
214 } else if (result.getException() instanceof DavException) {
215 syncResult.stats.numParseExceptions++;
216
217 } else if (result.getException() instanceof IOException) {
218 syncResult.stats.numIoExceptions++;
219
220 }
221 mFailedResultsCounter++;
222 mLastFailedResult = result;
223 }
224
225 }
226
227 /**
228 * Checks if a failed result should terminate the synchronization process immediately, according to
229 * OUR OWN POLICY
230 *
231 * @param failedResult Remote operation result to check.
232 * @return 'True' if the result should immediately finish the synchronization
233 */
234 private boolean isFinisher(RemoteOperationResult failedResult) {
235 if (failedResult != null) {
236 RemoteOperationResult.ResultCode code = failedResult.getCode();
237 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
238 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
239 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
240 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
241 }
242 return false;
243 }
244
245 /**
246 * Synchronize data of folders in the list of received files
247 *
248 * @param files Files to recursively fetch
249 * @param syncResult Updated object to provide results to the Synchronization Manager
250 */
251 private void fetchChildren(List<OCFile> files, SyncResult syncResult) {
252 int i;
253 for (i=0; i < files.size() && !mCancellation; i++) {
254 OCFile newFile = files.get(i);
255 if (newFile.isDirectory()) {
256 fetchData(newFile.getRemotePath(), syncResult, newFile.getFileId());
257 }
258 }
259 if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");
260 }
261
262
263 /**
264 * Sends a message to any application component interested in the progress of the synchronization.
265 *
266 * @param inProgress 'True' when the synchronization progress is not finished.
267 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
268 */
269 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
270 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
271 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
272 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
273 if (dirRemotePath != null) {
274 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
275 }
276 if (result != null) {
277 i.putExtra(FileSyncService.SYNC_RESULT, result);
278 }
279 getContext().sendStickyBroadcast(i);
280 }
281
282
283
284 /**
285 * Notifies the user about a failed synchronization through the status notification bar
286 */
287 private void notifyFailedSynchronization() {
288 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
289 notification.flags |= Notification.FLAG_AUTO_CANCEL;
290 // TODO put something smart in the contentIntent below
291 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
292 notification.setLatestEventInfo(getContext().getApplicationContext(),
293 getContext().getString(R.string.sync_fail_ticker),
294 String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
295 notification.contentIntent);
296 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
297 }
298
299
300
301 }