OC-1194: Adapt Sync Process using etag
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFolderOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.operations;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Vector;
31
32 import org.apache.http.HttpStatus;
33 import org.apache.jackrabbit.webdav.MultiStatus;
34 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
35
36 import android.accounts.Account;
37 import android.content.Context;
38 import android.os.storage.StorageManager;
39
40 import com.owncloud.android.Log_OC;
41 import com.owncloud.android.datamodel.DataStorageManager;
42 import com.owncloud.android.datamodel.OCFile;
43 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
44 import com.owncloud.android.utils.FileStorageUtils;
45
46 import eu.alefzero.webdav.WebdavClient;
47 import eu.alefzero.webdav.WebdavEntry;
48 import eu.alefzero.webdav.WebdavUtils;
49
50
51 /**
52 * Remote operation performing the synchronization a the contents of a remote folder with the local database
53 *
54 * @author David A. Velasco
55 */
56 public class SynchronizeFolderOperation extends RemoteOperation {
57
58 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
59
60 /** Remote folder to synchronize */
61 private String mRemotePath;
62
63 public String getRemotePath() {
64 return mRemotePath;
65 }
66
67
68 /** Timestamp for the synchronization in progress */
69 private long mCurrentSyncTime;
70
71 /** Id of the folder to synchronize in the local database */
72 private long mParentId;
73
74 public long getParentId() {
75 return mParentId;
76 }
77
78
79 /** Access to the local database */
80 private DataStorageManager mStorageManager;
81
82 /** Account where the file to synchronize belongs */
83 private Account mAccount;
84
85 /** Android context; necessary to send requests to the download service; maybe something to refactor */
86 private Context mContext;
87
88 /** Files and folders contained in the synchronized folder */
89 private List<OCFile> mChildren;
90
91 private int mConflictsFound;
92
93 private int mFailsInFavouritesFound;
94
95 private Map<String, String> mForgottenLocalFiles;
96
97
98 public SynchronizeFolderOperation( String remotePath,
99 long currentSyncTime,
100 long parentId,
101 DataStorageManager dataStorageManager,
102 Account account,
103 Context context ) {
104 mRemotePath = remotePath;
105 mCurrentSyncTime = currentSyncTime;
106 mParentId = parentId;
107 mStorageManager = dataStorageManager;
108 mAccount = account;
109 mContext = context;
110 mForgottenLocalFiles = new HashMap<String, String>();
111 }
112
113
114 public int getConflictsFound() {
115 return mConflictsFound;
116 }
117
118 public int getFailsInFavouritesFound() {
119 return mFailsInFavouritesFound;
120 }
121
122 public Map<String, String> getForgottenLocalFiles() {
123 return mForgottenLocalFiles;
124 }
125
126 /**
127 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
128 *
129 * @return List of files and folders contained in the synchronized folder.
130 */
131 public List<OCFile> getChildren() {
132 return mChildren;
133 }
134
135
136 @Override
137 protected RemoteOperationResult run(WebdavClient client) {
138 RemoteOperationResult result = null;
139 mFailsInFavouritesFound = 0;
140 mConflictsFound = 0;
141 mForgottenLocalFiles.clear();
142
143 // code before in FileSyncAdapter.fetchData
144 PropFindMethod query = null;
145 try {
146 Log_OC.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
147
148 // remote request
149 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
150 int status = client.executeMethod(query);
151
152 // check and process response - /// TODO take into account all the possible status per child-resource
153 if (isMultiStatus(status)) {
154 MultiStatus resp = query.getResponseBodyAsMultiStatus();
155
156 // synchronize properties of the parent folder, if necessary
157 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
158 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
159
160 // Properties of server folder
161 OCFile parent = fillOCFile(we);
162 // Properties of local folder
163 OCFile localParent = mStorageManager.getFileById(1);
164 if (parent.getEtag() != localParent.getEtag()) {
165 mStorageManager.saveFile(parent);
166 mParentId = parent.getFileId();
167 }
168 }
169
170
171 // read contents in folder
172 List<String> filesOnServer = new ArrayList<String> (); // Contains the lists of files on server
173 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
174 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
175 for (int i = 1; i < resp.getResponses().length; ++i) {
176 /// new OCFile instance with the data from the server
177 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
178 OCFile file = fillOCFile(we);
179
180 filesOnServer.add(file.getRemotePath()); // Registry the file in the list
181
182 /// set data about local state, keeping unchanged former data if existing
183 file.setLastSyncDateForProperties(mCurrentSyncTime);
184 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
185
186 // Check if it is needed to synchronize the folder
187 boolean fileChanged = false;
188 if (oldFile != null) {
189 if (!file.getEtag().equalsIgnoreCase(oldFile.getEtag())) {
190 fileChanged = true;
191 }
192 } else
193 fileChanged= true;
194
195 if (fileChanged){
196 if (oldFile != null) {
197 file.setKeepInSync(oldFile.keepInSync());
198 file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
199 file.setModificationTimestampAtLastSyncForData(oldFile.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
200 checkAndFixForeignStoragePath(oldFile);
201 file.setStoragePath(oldFile.getStoragePath());
202 }
203 /// scan default location if local copy of file is not linked in OCFile instance
204 if (file.getStoragePath() == null && !file.isDirectory()) {
205 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
206 if (f.exists()) {
207 file.setStoragePath(f.getAbsolutePath());
208 file.setLastSyncDateForData(f.lastModified());
209 }
210 }
211
212 /// prepare content synchronization for kept-in-sync files
213 if (file.keepInSync()) {
214 SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
215 file,
216 mStorageManager,
217 mAccount,
218 true,
219 false,
220 mContext
221 );
222 filesToSyncContents.add(operation);
223 }
224
225 updatedFiles.add(file);
226 }
227 }
228
229 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
230 mStorageManager.saveFiles(updatedFiles);
231
232 // request for the synchronization of files AFTER saving last properties
233 SynchronizeFileOperation op = null;
234 RemoteOperationResult contentsResult = null;
235 for (int i=0; i < filesToSyncContents.size(); i++) {
236 op = filesToSyncContents.get(i);
237 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
238 if (!contentsResult.isSuccess()) {
239 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
240 mConflictsFound++;
241 } else {
242 mFailsInFavouritesFound++;
243 if (contentsResult.getException() != null) {
244 Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
245 } else {
246 Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
247 }
248 }
249 } // won't let these fails break the synchronization process
250 }
251
252
253 // removal of obsolete files
254 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
255 OCFile file;
256 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
257 for (int i=0; i < mChildren.size(); ) {
258 file = mChildren.get(i);
259 //if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
260 if (!filesOnServer.contains(file.getRemotePath())) {
261 Log_OC.d(TAG, "removing file: " + file.getFileName());
262 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
263 mChildren.remove(i);
264 } else {
265 i++;
266 }
267 }
268
269 } else {
270 client.exhaustResponse(query.getResponseBodyAsStream());
271 }
272
273 // prepare result object
274 if (isMultiStatus(status)) {
275 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
276 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
277
278 } else {
279 result = new RemoteOperationResult(true, status);
280 }
281 } else {
282 result = new RemoteOperationResult(false, status);
283 }
284 Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
285
286
287 } catch (Exception e) {
288 result = new RemoteOperationResult(e);
289 Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
290
291 } finally {
292 if (query != null)
293 query.releaseConnection(); // let the connection available for other methods
294 }
295
296 return result;
297 }
298
299
300 public boolean isMultiStatus(int status) {
301 return (status == HttpStatus.SC_MULTI_STATUS);
302 }
303
304
305 /**
306 * Creates and populates a new {@link OCFile} object with the data read from the server.
307 *
308 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
309 * @return New OCFile instance representing the remote resource described by we.
310 */
311 private OCFile fillOCFile(WebdavEntry we) {
312 OCFile file = new OCFile(we.decodedPath());
313 file.setCreationTimestamp(we.createTimestamp());
314 file.setFileLength(we.contentLength());
315 file.setMimetype(we.contentType());
316 file.setModificationTimestamp(we.modifiedTimestamp());
317 file.setParentId(mParentId);
318 file.setEtag(we.etag());
319 return file;
320 }
321
322
323 /**
324 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
325 * tries to copy the file inside it.
326 *
327 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
328 * {@link #mForgottenLocalFiles}
329 *
330 * @param file File to check and fix.
331 */
332 private void checkAndFixForeignStoragePath(OCFile file) {
333 String storagePath = file.getStoragePath();
334 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
335 if (storagePath != null && !storagePath.equals(expectedPath)) {
336 /// fix storagePaths out of the local ownCloud folder
337 File originalFile = new File(storagePath);
338 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
339 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
340 file.setStoragePath(null);
341
342 } else {
343 InputStream in = null;
344 OutputStream out = null;
345 try {
346 File expectedFile = new File(expectedPath);
347 File expectedParent = expectedFile.getParentFile();
348 expectedParent.mkdirs();
349 if (!expectedParent.isDirectory()) {
350 throw new IOException("Unexpected error: parent directory could not be created");
351 }
352 expectedFile.createNewFile();
353 if (!expectedFile.isFile()) {
354 throw new IOException("Unexpected error: target file could not be created");
355 }
356 in = new FileInputStream(originalFile);
357 out = new FileOutputStream(expectedFile);
358 byte[] buf = new byte[1024];
359 int len;
360 while ((len = in.read(buf)) > 0){
361 out.write(buf, 0, len);
362 }
363 file.setStoragePath(expectedPath);
364
365 } catch (Exception e) {
366 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
367 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
368 file.setStoragePath(null);
369
370 } finally {
371 try {
372 if (in != null) in.close();
373 } catch (Exception e) {
374 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
375 }
376 try {
377 if (out != null) out.close();
378 } catch (Exception e) {
379 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
380 }
381 }
382 }
383 }
384 }
385
386
387 }