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