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