3c9c6544e7db7ba9e6ce97d2e015638b2d4c8403
[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.content.Intent;
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.syncadapter.FileSyncService;
45 import com.owncloud.android.utils.FileStorageUtils;
46
47 import eu.alefzero.webdav.WebdavClient;
48 import eu.alefzero.webdav.WebdavEntry;
49 import eu.alefzero.webdav.WebdavUtils;
50
51
52 /**
53 * Remote operation performing the synchronization a the contents of a remote folder with the local database
54 *
55 * @author David A. Velasco
56 */
57 public class SynchronizeFolderOperation extends RemoteOperation {
58
59 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
60
61 /** Remote folder to synchronize */
62 private String mRemotePath;
63
64 /** Timestamp for the synchronization in progress */
65 private long mCurrentSyncTime;
66
67 /** Id of the folder to synchronize in the local database */
68 private long mParentId;
69
70 /** Boolean to indicate if is mandatory to update the folder */
71 private boolean mEnforceMetadataUpdate;
72
73 /** Access to the local database */
74 private DataStorageManager mStorageManager;
75
76 /** Account where the file to synchronize belongs */
77 private Account mAccount;
78
79 /** Android context; necessary to send requests to the download service; maybe something to refactor */
80 private Context mContext;
81
82 /** Files and folders contained in the synchronized folder */
83 private List<OCFile> mChildren;
84
85 private int mConflictsFound;
86
87 private int mFailsInFavouritesFound;
88
89 private Map<String, String> mForgottenLocalFiles;
90
91 private boolean mSyncFullAccount;
92
93
94 public SynchronizeFolderOperation( String remotePath,
95 long currentSyncTime,
96 long parentId,
97 boolean enforceMetadataUpdate,
98 boolean syncFullAccount,
99 DataStorageManager dataStorageManager,
100 Account account,
101 Context context ) {
102 mRemotePath = remotePath;
103 mCurrentSyncTime = currentSyncTime;
104 mParentId = parentId;
105 mEnforceMetadataUpdate = enforceMetadataUpdate;
106 mSyncFullAccount = syncFullAccount;
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 public String getRemotePath() {
136 return mRemotePath;
137 }
138
139 public long getParentId() {
140 return mParentId;
141 }
142
143 @Override
144 protected RemoteOperationResult run(WebdavClient client) {
145 RemoteOperationResult result = null;
146 mFailsInFavouritesFound = 0;
147 mConflictsFound = 0;
148 mForgottenLocalFiles.clear();
149 boolean dirChanged = false;
150
151 // code before in FileSyncAdapter.fetchData
152 PropFindMethod query = null;
153 try {
154 Log_OC.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
155
156 // remote request
157 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
158 int status = client.executeMethod(query);
159
160 // check and process response - /// TODO take into account all the possible status per child-resource
161 if (isMultiStatus(status)) {
162 MultiStatus resp = query.getResponseBodyAsMultiStatus();
163
164 // synchronize properties of the parent folder, if necessary
165 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
166
167 // Properties of server folder
168 OCFile parent = fillOCFile(we);
169 // Properties of local folder
170 OCFile localParent = mStorageManager.getFileByPath(mRemotePath);
171 if (localParent == null || !(parent.getEtag().equalsIgnoreCase(localParent.getEtag())) || mEnforceMetadataUpdate) {
172 if (localParent != null) {
173 parent.setParentId(localParent.getParentId());
174 }
175 mStorageManager.saveFile(parent);
176 if (mParentId == DataStorageManager.ROOT_PARENT_ID)
177 mParentId = parent.getFileId();
178 dirChanged = true;
179 }
180
181 if (dirChanged) {
182 // read contents in folder
183 List<String> filesOnServer = new ArrayList<String> (); // Contains the lists of files on server
184 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
185 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
186 for (int i = 1; i < resp.getResponses().length; ++i) {
187 /// new OCFile instance with the data from the server
188 we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
189 OCFile file = fillOCFile(we);
190
191 filesOnServer.add(file.getRemotePath()); // Registry the file in the list
192
193 /// set data about local state, keeping unchanged former data if existing
194 file.setLastSyncDateForProperties(mCurrentSyncTime);
195 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
196
197 // Check if it is needed to synchronize the folder
198 if (oldFile != null) {
199 if (!file.getEtag().equalsIgnoreCase(oldFile.getEtag())) {
200 }
201 }
202
203 if (oldFile != null) {
204 file.setKeepInSync(oldFile.keepInSync());
205 file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
206 file.setModificationTimestampAtLastSyncForData(oldFile.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
207 checkAndFixForeignStoragePath(oldFile);
208 file.setStoragePath(oldFile.getStoragePath());
209 if (file.isDirectory())
210 file.setEtag(oldFile.getEtag());
211 } else
212 if (file.isDirectory())
213 file.setEtag("");
214
215 /// scan default location if local copy of file is not linked in OCFile instance
216 if (file.getStoragePath() == null && !file.isDirectory()) {
217 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
218 if (f.exists()) {
219 file.setStoragePath(f.getAbsolutePath());
220 file.setLastSyncDateForData(f.lastModified());
221 }
222 }
223
224 /// prepare content synchronization for kept-in-sync files
225 if (file.keepInSync()) {
226 SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
227 file,
228 mStorageManager,
229 mAccount,
230 true,
231 false,
232 mContext
233 );
234 filesToSyncContents.add(operation);
235 }
236
237 updatedFiles.add(file);
238 }
239
240 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
241 mStorageManager.saveFiles(updatedFiles);
242
243 // request for the synchronization of files AFTER saving last properties
244 RemoteOperationResult contentsResult = null;
245 for (SynchronizeFileOperation op: filesToSyncContents) {
246 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
247 if (!contentsResult.isSuccess()) {
248 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
249 mConflictsFound++;
250 } else {
251 mFailsInFavouritesFound++;
252 if (contentsResult.getException() != null) {
253 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
254 } else {
255 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
256 }
257 }
258 } // won't let these fails break the synchronization process
259 }
260
261 // removal of obsolete files
262 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
263 OCFile file;
264 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
265 for (int i=0; i < mChildren.size(); ) {
266 file = mChildren.get(i);
267 if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
268 Log_OC.d(TAG, "removing file: " + file);
269 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
270 mChildren.remove(i);
271 } else {
272 i++;
273 }
274 }
275
276 } else {
277 client.exhaustResponse(query.getResponseBodyAsStream());
278 }
279
280
281 // prepare result object
282 if (!dirChanged) {
283 result = new RemoteOperationResult(ResultCode.OK_NO_CHANGES_ON_DIR);
284 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
285
286 } else {
287 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
288 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
289
290 } else {
291 result = new RemoteOperationResult(true, status, query.getResponseHeaders());
292 }
293 }
294
295 } else {
296 if (status == HttpStatus.SC_NOT_FOUND) {
297 OCFile dir = mStorageManager.getFileByPath(mRemotePath);
298 if (dir != null) {
299 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
300 mStorageManager.removeDirectory(dir, true, (dir.isDown() && dir.getStoragePath().startsWith(currentSavePath)));
301 }
302 }
303 result = new RemoteOperationResult(false, status, query.getResponseHeaders());
304 }
305
306 } catch (Exception e) {
307 result = new RemoteOperationResult(e);
308
309
310 } finally {
311 if (query != null)
312 query.releaseConnection(); // let the connection available for other methods
313 if (result.isSuccess()) {
314 Log_OC.i(TAG, "Synchroned " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
315 } else {
316 if (result.isException()) {
317 Log_OC.e(TAG, "Synchroned " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
318 } else {
319 Log_OC.e(TAG, "Synchroned " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
320 }
321 }
322
323 if (!mSyncFullAccount) {
324 sendStickyBroadcast(false, mRemotePath, result);
325 }
326 }
327
328 return result;
329 }
330
331
332 public boolean isMultiStatus(int status) {
333 return (status == HttpStatus.SC_MULTI_STATUS);
334 }
335
336
337 /**
338 * Creates and populates a new {@link OCFile} object with the data read from the server.
339 *
340 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
341 * @return New OCFile instance representing the remote resource described by we.
342 */
343 private OCFile fillOCFile(WebdavEntry we) {
344 OCFile file = new OCFile(we.decodedPath());
345 file.setCreationTimestamp(we.createTimestamp());
346 file.setFileLength(we.contentLength());
347 file.setMimetype(we.contentType());
348 file.setModificationTimestamp(we.modifiedTimestamp());
349 file.setParentId(mParentId);
350 file.setEtag(we.etag());
351 return file;
352 }
353
354
355 /**
356 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
357 * tries to copy the file inside it.
358 *
359 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
360 * {@link #mForgottenLocalFiles}
361 *)
362 * @param file File to check and fix.
363 */
364 private void checkAndFixForeignStoragePath(OCFile file) {
365 String storagePath = file.getStoragePath();
366 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
367 if (storagePath != null && !storagePath.equals(expectedPath)) {
368 /// fix storagePaths out of the local ownCloud folder
369 File originalFile = new File(storagePath);
370 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
371 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
372 file.setStoragePath(null);
373
374 } else {
375 InputStream in = null;
376 OutputStream out = null;
377 try {
378 File expectedFile = new File(expectedPath);
379 File expectedParent = expectedFile.getParentFile();
380 expectedParent.mkdirs();
381 if (!expectedParent.isDirectory()) {
382 throw new IOException("Unexpected error: parent directory could not be created");
383 }
384 expectedFile.createNewFile();
385 if (!expectedFile.isFile()) {
386 throw new IOException("Unexpected error: target file could not be created");
387 }
388 in = new FileInputStream(originalFile);
389 out = new FileOutputStream(expectedFile);
390 byte[] buf = new byte[1024];
391 int len;
392 while ((len = in.read(buf)) > 0){
393 out.write(buf, 0, len);
394 }
395 file.setStoragePath(expectedPath);
396
397 } catch (Exception e) {
398 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
399 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
400 file.setStoragePath(null);
401
402 } finally {
403 try {
404 if (in != null) in.close();
405 } catch (Exception e) {
406 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
407 }
408 try {
409 if (out != null) out.close();
410 } catch (Exception e) {
411 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
412 }
413 }
414 }
415 }
416 }
417
418 /**
419 * Sends a message to any application component interested in the progress of the synchronization.
420 *
421 * @param inProgress 'True' when the synchronization progress is not finished.
422 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
423 */
424 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
425 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
426 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
427 i.putExtra(FileSyncService.ACCOUNT_NAME, mAccount.name);
428 if (dirRemotePath != null) {
429 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
430 }
431 if (result != null) {
432 i.putExtra(FileSyncService.SYNC_RESULT, result);
433 }
434 mContext.sendStickyBroadcast(i);
435 }
436
437 }