OC-1388: Refresh
[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 com.owncloud.android.Log_OC;
39 import com.owncloud.android.datamodel.DataStorageManager;
40 import com.owncloud.android.datamodel.OCFile;
41 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.utils.FileStorageUtils;
43
44 import eu.alefzero.webdav.WebdavClient;
45 import eu.alefzero.webdav.WebdavEntry;
46 import eu.alefzero.webdav.WebdavUtils;
47
48
49 /**
50 * Remote operation performing the synchronization a the contents of a remote folder with the local database
51 *
52 * @author David A. Velasco
53 */
54 public class SynchronizeFolderOperation extends RemoteOperation {
55
56 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
57
58 /** Remote folder to synchronize */
59 private String mRemotePath;
60
61 /** Timestamp for the synchronization in progress */
62 private long mCurrentSyncTime;
63
64 /** Id of the folder to synchronize in the local database */
65 private long mParentId;
66
67 /** Access to the local database */
68 private DataStorageManager mStorageManager;
69
70 /** Account where the file to synchronize belongs */
71 private Account mAccount;
72
73 /** Android context; necessary to send requests to the download service; maybe something to refactor */
74 private Context mContext;
75
76 /** Files and folders contained in the synchronized folder */
77 private List<OCFile> mChildren;
78
79 private int mConflictsFound;
80
81 private int mFailsInFavouritesFound;
82
83 private Map<String, String> mForgottenLocalFiles;
84
85
86 public SynchronizeFolderOperation( String remotePath,
87 long currentSyncTime,
88 long parentId,
89 DataStorageManager dataStorageManager,
90 Account account,
91 Context context ) {
92 mRemotePath = remotePath;
93 mCurrentSyncTime = currentSyncTime;
94 mParentId = parentId;
95 mStorageManager = dataStorageManager;
96 mAccount = account;
97 mContext = context;
98 mForgottenLocalFiles = new HashMap<String, String>();
99 }
100
101
102 public int getConflictsFound() {
103 return mConflictsFound;
104 }
105
106 public int getFailsInFavouritesFound() {
107 return mFailsInFavouritesFound;
108 }
109
110 public Map<String, String> getForgottenLocalFiles() {
111 return mForgottenLocalFiles;
112 }
113
114 /**
115 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
116 *
117 * @return List of files and folders contained in the synchronized folder.
118 */
119 public List<OCFile> getChildren() {
120 return mChildren;
121 }
122
123 public String getRemotePath() {
124 return mRemotePath;
125 }
126
127 public long getParentId() {
128 return mParentId;
129 }
130
131 @Override
132 protected RemoteOperationResult run(WebdavClient client) {
133 RemoteOperationResult result = null;
134 mFailsInFavouritesFound = 0;
135 mConflictsFound = 0;
136 mForgottenLocalFiles.clear();
137 boolean fileChanged = false;
138 boolean dirChanged = true;
139
140 // code before in FileSyncAdapter.fetchData
141 PropFindMethod query = null;
142 try {
143 Log_OC.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
144
145 // remote request
146 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
147 int status = client.executeMethod(query);
148
149 // check and process response - /// TODO take into account all the possible status per child-resource
150 if (isMultiStatus(status)) {
151 MultiStatus resp = query.getResponseBodyAsMultiStatus();
152
153 // synchronize properties of the parent folder, if necessary
154 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
155 dirChanged = false;
156 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
157
158 // Properties of server folder
159 OCFile parent = fillOCFile(we);
160 // Properties of local folder
161 OCFile localParent = mStorageManager.getFileById(1);
162 if (localParent == null || !(parent.getEtag().equalsIgnoreCase(localParent.getEtag()))) {
163 mStorageManager.saveFile(parent);
164 mParentId = parent.getFileId();
165 dirChanged = true;
166 }
167 }
168 else if (! mRemotePath.equalsIgnoreCase(OCFile.PATH_SEPARATOR)){
169 dirChanged = false;
170 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
171
172 // Properties of server folder
173 OCFile parent = fillOCFile(we);
174 // Properties of local folder
175 OCFile localParent = mStorageManager.getFileByPath(mRemotePath);
176 if (localParent == null || !(parent.getEtag().equalsIgnoreCase(localParent.getEtag()))) {
177 dirChanged = true;
178 }
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 WebdavEntry 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 fileChanged = false;
199 if (oldFile != null) {
200 if (!file.getEtag().equalsIgnoreCase(oldFile.getEtag())) {
201 fileChanged = true;
202 }
203 } else
204 fileChanged= true;
205
206 if (fileChanged){
207 if (file.isDirectory())
208 file.setEtag("");
209 if (oldFile != null) {
210 file.setKeepInSync(oldFile.keepInSync());
211 file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
212 file.setModificationTimestampAtLastSyncForData(oldFile.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
213 checkAndFixForeignStoragePath(oldFile);
214 file.setStoragePath(oldFile.getStoragePath());
215 }
216 /// scan default location if local copy of file is not linked in OCFile instance
217 if (file.getStoragePath() == null && !file.isDirectory()) {
218 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
219 if (f.exists()) {
220 file.setStoragePath(f.getAbsolutePath());
221 file.setLastSyncDateForData(f.lastModified());
222 }
223 }
224
225 /// prepare content synchronization for kept-in-sync files
226 if (file.keepInSync()) {
227 SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
228 file,
229 mStorageManager,
230 mAccount,
231 true,
232 false,
233 mContext
234 );
235 filesToSyncContents.add(operation);
236 }
237
238 updatedFiles.add(file);
239 }
240 }
241
242 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
243 mStorageManager.saveFiles(updatedFiles);
244
245 // request for the synchronization of files AFTER saving last properties
246 RemoteOperationResult contentsResult = null;
247 for (SynchronizeFileOperation op: filesToSyncContents) {//int i=0; i < filesToSyncContents.size(); i++) {
248 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
249 if (!contentsResult.isSuccess()) {
250 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
251 mConflictsFound++;
252 } else {
253 mFailsInFavouritesFound++;
254 if (contentsResult.getException() != null) {
255 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
256 } else {
257 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
258 }
259 }
260 } // won't let these fails break the synchronization process
261 }
262
263
264 // removal of obsolete files
265 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
266 //OCFile file;
267 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
268 for (OCFile fileChild: mChildren) {
269 if (!filesOnServer.contains(fileChild.getRemotePath())) {
270 Log_OC.d(TAG, "removing file: " + fileChild.getFileName());
271 mStorageManager.removeFile(fileChild, (fileChild.isDown() && fileChild.getStoragePath().startsWith(currentSavePath)));
272 // mChildren.remove(fileChild); //.remove(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 if (isMultiStatus(status)) {
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 } else {
294 result = new RemoteOperationResult(false, status, query.getResponseHeaders());
295 }
296 Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
297
298 } catch (Exception e) {
299 result = new RemoteOperationResult(e);
300
301
302 } finally {
303 if (query != null)
304 query.releaseConnection(); // let the connection available for other methods
305 if (result.isSuccess()) {
306 Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
307 } else {
308 if (result.isException()) {
309 Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
310 } else {
311 Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
312 }
313 }
314 }
315
316 return result;
317 }
318
319
320 public boolean isMultiStatus(int status) {
321 return (status == HttpStatus.SC_MULTI_STATUS);
322 }
323
324
325 /**
326 * Creates and populates a new {@link OCFile} object with the data read from the server.
327 *
328 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
329 * @return New OCFile instance representing the remote resource described by we.
330 */
331 private OCFile fillOCFile(WebdavEntry we) {
332 OCFile file = new OCFile(we.decodedPath());
333 file.setCreationTimestamp(we.createTimestamp());
334 file.setFileLength(we.contentLength());
335 file.setMimetype(we.contentType());
336 file.setModificationTimestamp(we.modifiedTimestamp());
337 file.setParentId(mParentId);
338 file.setEtag(we.etag());
339 return file;
340 }
341
342
343 /**
344 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
345 * tries to copy the file inside it.
346 *
347 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
348 * {@link #mForgottenLocalFiles}
349 *)
350 * @param file File to check and fix.
351 */
352 private void checkAndFixForeignStoragePath(OCFile file) {
353 String storagePath = file.getStoragePath();
354 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
355 if (storagePath != null && !storagePath.equals(expectedPath)) {
356 /// fix storagePaths out of the local ownCloud folder
357 File originalFile = new File(storagePath);
358 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
359 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
360 file.setStoragePath(null);
361
362 } else {
363 InputStream in = null;
364 OutputStream out = null;
365 try {
366 File expectedFile = new File(expectedPath);
367 File expectedParent = expectedFile.getParentFile();
368 expectedParent.mkdirs();
369 if (!expectedParent.isDirectory()) {
370 throw new IOException("Unexpected error: parent directory could not be created");
371 }
372 expectedFile.createNewFile();
373 if (!expectedFile.isFile()) {
374 throw new IOException("Unexpected error: target file could not be created");
375 }
376 in = new FileInputStream(originalFile);
377 out = new FileOutputStream(expectedFile);
378 byte[] buf = new byte[1024];
379 int len;
380 while ((len = in.read(buf)) > 0){
381 out.write(buf, 0, len);
382 }
383 file.setStoragePath(expectedPath);
384
385 } catch (Exception e) {
386 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
387 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
388 file.setStoragePath(null);
389
390 } finally {
391 try {
392 if (in != null) in.close();
393 } catch (Exception e) {
394 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
395 }
396 try {
397 if (out != null) out.close();
398 } catch (Exception e) {
399 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
400 }
401 }
402 }
403 }
404 }
405
406
407 }