c5776de120e95b1f4167ad27fe37e19ad4d0d8ed
[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 private long mCurrentSyncTime;
61 private boolean mCancellation;
62 private boolean mIsManualSync;
63 private boolean mRightSync;
64
65 public FileSyncAdapter(Context context, boolean autoInitialize) {
66 super(context, autoInitialize);
67 }
68
69 @Override
70 public synchronized void onPerformSync(Account account, Bundle extras,
71 String authority, ContentProviderClient provider,
72 SyncResult syncResult) {
73
74 mCancellation = false;
75 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
76 mRightSync = true;
77
78 this.setAccount(account);
79 this.setContentProvider(provider);
80 this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
81
82 Log.d(TAG, "syncing owncloud account " + account.name);
83
84 sendStickyBroadcast(true, null); // message to signal the start to the UI
85
86 try {
87 updateOCVersion();
88 mCurrentSyncTime = System.currentTimeMillis();
89 if (!mCancellation) {
90 fetchData(OCFile.PATH_SEPARATOR, syncResult, DataStorageManager.ROOT_PARENT_ID);
91
92 } else {
93 Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");
94 }
95
96 } finally {
97 // it's important making this although very unexpected errors occur; that's the reason for the finally
98
99 mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0);
100 if (!mRightSync && mIsManualSync) {
101 /// don't let the system synchronization manager retries MANUAL synchronizations
102 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
103 syncResult.tooManyRetries = true;
104
105 /// notify the user about the failure of MANUAL synchronization
106 notifyFailedSynchronization();
107 }
108 sendStickyBroadcast(false, null); // message to signal the end to the UI
109 }
110
111 }
112
113
114
115 /**
116 * Called by system SyncManager when a synchronization is required to be cancelled.
117 *
118 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
119 * fetched will be still saved in the database. See onPerformSync implementation.
120 */
121 @Override
122 public void onSyncCanceled() {
123 Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
124 mCancellation = true;
125 super.onSyncCanceled();
126 }
127
128
129 /**
130 * Updates the locally stored version value of the ownCloud server
131 */
132 private void updateOCVersion() {
133 String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);
134 statUrl += AccountUtils.STATUS_PATH;
135
136 try {
137 String result = getClient().getResultAsString(statUrl);
138 if (result != null) {
139 try {
140 JSONObject json = new JSONObject(result);
141 if (json != null && json.getString("version") != null) {
142 OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));
143 if (ocver.isVersionValid()) {
144 getAccountManager().setUserData(getAccount(), AccountAuthenticator.KEY_OC_VERSION, ocver.toString());
145 Log.d(TAG, "Got new OC version " + ocver.toString());
146 } else {
147 Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));
148 }
149 }
150 } catch (Throwable e) {
151 Log.w(TAG, "Couldn't parse version response", e);
152 }
153 } else {
154 Log.w(TAG, "Problem while getting ocversion from server");
155 }
156 } catch (Exception e) {
157 Log.e(TAG, "Problem getting response from server", e);
158 }
159 }
160
161
162
163 /**
164 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
165 *
166 * @param remotePath Remote path to the folder to synchronize.
167 * @param parentId Database Id of the folder to synchronize.
168 * @param syncResult Object to update for communicate results to the system's synchronization manager.
169 */
170 private void fetchData(String remotePath, SyncResult syncResult, long parentId) {
171
172 // get client object to connect to the remote ownCloud server
173 WebdavClient client = null;
174 try {
175 client = getClient();
176 } catch (IOException e) {
177 syncResult.stats.numIoExceptions++;
178 Log.d(TAG, "Could not get client object while trying to synchronize - impossible to continue");
179 return;
180 }
181
182 // perform folder synchronization
183 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath,
184 mCurrentSyncTime,
185 parentId,
186 getStorageManager(),
187 getAccount(),
188 getContext()
189 );
190 RemoteOperationResult result = synchFolderOp.execute(client);
191
192
193 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
194 sendStickyBroadcast(true, remotePath);
195
196 if (result.isSuccess()) {
197 // synchronize children folders
198 List<OCFile> children = synchFolderOp.getChildren();
199 fetchChildren(children, syncResult); // beware of the 'hidden' recursion here!
200
201 } else {
202 if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
203 syncResult.stats.numAuthExceptions++;
204
205 } else if (result.getException() instanceof DavException) {
206 syncResult.stats.numParseExceptions++;
207
208 } else if (result.getException() instanceof IOException) {
209 syncResult.stats.numIoExceptions++;
210
211 } else if (result.getException() != null) {
212 // TODO maybe something smarter with syncResult
213 mRightSync = false;
214 }
215 }
216
217 }
218
219 /**
220 * Synchronize data of folders in the list of received files
221 *
222 * @param files Files to recursively fetch
223 * @param syncResult Updated object to provide results to the Synchronization Manager
224 */
225 private void fetchChildren(List<OCFile> files, SyncResult syncResult) {
226 int i;
227 for (i=0; i < files.size() && !mCancellation; i++) {
228 OCFile newFile = files.get(i);
229 if (newFile.isDirectory()) {
230 fetchData(newFile.getRemotePath(), syncResult, newFile.getFileId());
231 }
232 }
233 if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");
234 }
235
236
237 /**
238 * Sends a message to any app component interested in the progress of the synchronization.
239 *
240 * @param inProgress 'True' when the synchronization progress is not finished.
241 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
242 */
243 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath/*, RemoteOperationResult result*/) {
244 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
245 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
246 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
247 if (dirRemotePath != null) {
248 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
249 }
250 /*if (result != null) {
251 i.putExtra(FileSyncService.SYNC_RESULT, result);
252 }*/
253 getContext().sendStickyBroadcast(i);
254 }
255
256
257
258 /**
259 * Notifies the user about a failed synchronization through the status notification bar
260 */
261 private void notifyFailedSynchronization() {
262 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
263 notification.flags |= Notification.FLAG_AUTO_CANCEL;
264 // TODO put something smart in the contentIntent below
265 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
266 notification.setLatestEventInfo(getContext().getApplicationContext(),
267 getContext().getString(R.string.sync_fail_ticker),
268 String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
269 notification.contentIntent);
270 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
271 }
272
273
274
275 }