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