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