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