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