Workaround to show hidden accents in options menu
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFolderOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 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.operations;
20
21 import java.io.File;
22 import java.util.List;
23 import java.util.Vector;
24
25 import org.apache.http.HttpStatus;
26 import org.apache.jackrabbit.webdav.MultiStatus;
27 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
28
29 import android.accounts.Account;
30 import android.content.Context;
31 import android.util.Log;
32
33 import com.owncloud.android.datamodel.DataStorageManager;
34 import com.owncloud.android.datamodel.OCFile;
35 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
36 import com.owncloud.android.utils.FileStorageUtils;
37
38 import eu.alefzero.webdav.WebdavClient;
39 import eu.alefzero.webdav.WebdavEntry;
40 import eu.alefzero.webdav.WebdavUtils;
41
42
43 /**
44 * Remote operation performing the synchronization a the contents of a remote folder with the local database
45 *
46 * @author David A. Velasco
47 */
48 public class SynchronizeFolderOperation extends RemoteOperation {
49
50 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
51
52 /** Remote folder to synchronize */
53 private String mRemotePath;
54
55 /** Timestamp for the synchronization in progress */
56 private long mCurrentSyncTime;
57
58 /** Id of the folder to synchronize in the local database */
59 private long mParentId;
60
61 /** Access to the local database */
62 private DataStorageManager mStorageManager;
63
64 /** Account where the file to synchronize belongs */
65 private Account mAccount;
66
67 /** Android context; necessary to send requests to the download service; maybe something to refactor */
68 private Context mContext;
69
70 /** Files and folders contained in the synchronized folder */
71 private List<OCFile> mChildren;
72
73 private int mConflictsFound;
74
75 private int mFailsInFavouritesFound;
76
77
78 public SynchronizeFolderOperation( String remotePath,
79 long currentSyncTime,
80 long parentId,
81 DataStorageManager dataStorageManager,
82 Account account,
83 Context context ) {
84 mRemotePath = remotePath;
85 mCurrentSyncTime = currentSyncTime;
86 mParentId = parentId;
87 mStorageManager = dataStorageManager;
88 mAccount = account;
89 mContext = context;
90 }
91
92
93 public int getConflictsFound() {
94 return mConflictsFound;
95 }
96
97 public int getFailsInFavouritesFound() {
98 return mFailsInFavouritesFound;
99 }
100
101 /**
102 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
103 *
104 * @return List of files and folders contained in the synchronized folder.
105 */
106 public List<OCFile> getChildren() {
107 return mChildren;
108 }
109
110
111 @Override
112 protected RemoteOperationResult run(WebdavClient client) {
113 RemoteOperationResult result = null;
114 mFailsInFavouritesFound = 0;
115 mConflictsFound = 0;
116
117 // code before in FileSyncAdapter.fetchData
118 PropFindMethod query = null;
119 try {
120 Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
121
122 // remote request
123 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
124 int status = client.executeMethod(query);
125
126 // check and process response - /// TODO take into account all the possible status per child-resource
127 if (isMultiStatus(status)) {
128 MultiStatus resp = query.getResponseBodyAsMultiStatus();
129
130 // synchronize properties of the parent folder, if necessary
131 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
132 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
133 OCFile parent = fillOCFile(we);
134 mStorageManager.saveFile(parent);
135 mParentId = parent.getFileId();
136 }
137
138 // read contents in folder
139 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
140 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
141 for (int i = 1; i < resp.getResponses().length; ++i) {
142 /// new OCFile instance with the data from the server
143 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
144 OCFile file = fillOCFile(we);
145
146 /// set data about local state, keeping unchanged former data if existing
147 file.setLastSyncDateForProperties(mCurrentSyncTime);
148 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
149 if (oldFile != null) {
150 file.setKeepInSync(oldFile.keepInSync());
151 file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
152 file.setStoragePath(oldFile.getStoragePath());
153 }
154
155 /// scan default location if local copy of file is not linked in OCFile instance
156 if (file.getStoragePath() == null && !file.isDirectory()) {
157 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
158 if (f.exists()) {
159 file.setStoragePath(f.getAbsolutePath());
160 file.setLastSyncDateForData(f.lastModified());
161 }
162 }
163
164 /// prepare content synchronization for kept-in-sync files
165 if (file.keepInSync()) {
166 SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
167 file,
168 mStorageManager,
169 mAccount,
170 true,
171 false,
172 mContext
173 );
174 filesToSyncContents.add(operation);
175 }
176
177 updatedFiles.add(file);
178 }
179
180 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
181 mStorageManager.saveFiles(updatedFiles);
182
183 // request for the synchronization of files AFTER saving last properties
184 SynchronizeFileOperation op = null;
185 RemoteOperationResult contentsResult = null;
186 for (int i=0; i < filesToSyncContents.size(); i++) {
187 op = filesToSyncContents.get(i);
188 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
189 if (!contentsResult.isSuccess()) {
190 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
191 mConflictsFound++;
192 } else {
193 mFailsInFavouritesFound++;
194 if (contentsResult.getException() != null) {
195 Log.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
196 } else {
197 Log.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
198 }
199 }
200 } // won't let these fails break the synchronization process
201 }
202
203
204 // removal of obsolete files
205 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
206 OCFile file;
207 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
208 for (int i=0; i < mChildren.size(); ) {
209 file = mChildren.get(i);
210 if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
211 Log.d(TAG, "removing file: " + file);
212 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
213 mChildren.remove(i);
214 } else {
215 i++;
216 }
217 }
218
219 } else {
220 client.exhaustResponse(query.getResponseBodyAsStream());
221 }
222
223 // prepare result object
224 if (isMultiStatus(status)) {
225 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
226 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
227
228 } else {
229 result = new RemoteOperationResult(true, status);
230 }
231 } else {
232 result = new RemoteOperationResult(false, status);
233 }
234 Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
235
236
237 } catch (Exception e) {
238 result = new RemoteOperationResult(e);
239 Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
240
241 } finally {
242 if (query != null)
243 query.releaseConnection(); // let the connection available for other methods
244 }
245
246 return result;
247 }
248
249
250 public boolean isMultiStatus(int status) {
251 return (status == HttpStatus.SC_MULTI_STATUS);
252 }
253
254
255 /**
256 * Creates and populates a new {@link OCFile} object with the data read from the server.
257 *
258 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
259 * @return New OCFile instance representing the remote resource described by we.
260 */
261 private OCFile fillOCFile(WebdavEntry we) {
262 OCFile file = new OCFile(we.decodedPath());
263 file.setCreationTimestamp(we.createTimestamp());
264 file.setFileLength(we.contentLength());
265 file.setMimetype(we.contentType());
266 file.setModificationTimestamp(we.modifiedTimesamp());
267 file.setParentId(mParentId);
268 return file;
269 }
270
271
272 }