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