Synchronize kept-in-sync files during account synchronization, in both directions...
[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.util.List;
22 import java.util.Vector;
23
24 import org.apache.http.HttpStatus;
25 import org.apache.jackrabbit.webdav.MultiStatus;
26 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
27
28 import android.accounts.Account;
29 import android.content.Context;
30 import android.util.Log;
31
32 import com.owncloud.android.datamodel.DataStorageManager;
33 import com.owncloud.android.datamodel.OCFile;
34 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
35 import com.owncloud.android.utils.FileStorageUtils;
36
37 import eu.alefzero.webdav.WebdavClient;
38 import eu.alefzero.webdav.WebdavEntry;
39 import eu.alefzero.webdav.WebdavUtils;
40
41
42 /**
43 * Remote operation performing the synchronization a the contents of a remote folder with the local database
44 *
45 * @author David A. Velasco
46 */
47 public class SynchronizeFolderOperation extends RemoteOperation {
48
49 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
50
51 /** Remote folder to synchronize */
52 private String mRemotePath;
53
54 /** Timestamp for the synchronization in progress */
55 private long mCurrentSyncTime;
56
57 /** Id of the folder to synchronize in the local database */
58 private long mParentId;
59
60 /** Access to the local database */
61 private DataStorageManager mStorageManager;
62
63 /** Account where the file to synchronize belongs */
64 private Account mAccount;
65
66 /** Android context; necessary to send requests to the download service; maybe something to refactor */
67 private Context mContext;
68
69 /** Files and folders contained in the synchronized folder */
70 private List<OCFile> mChildren;
71
72 private int mConflictsFound;
73
74 private int mFailsInFavouritesFound;
75
76
77 public SynchronizeFolderOperation( String remotePath,
78 long currentSyncTime,
79 long parentId,
80 DataStorageManager dataStorageManager,
81 Account account,
82 Context context ) {
83 mRemotePath = remotePath;
84 mCurrentSyncTime = currentSyncTime;
85 mParentId = parentId;
86 mStorageManager = dataStorageManager;
87 mAccount = account;
88 mContext = context;
89 }
90
91
92 public int getConflictsFound() {
93 return mConflictsFound;
94 }
95
96 public int getFailsInFavouritesFound() {
97 return mFailsInFavouritesFound;
98 }
99
100 /**
101 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
102 *
103 * @return List of files and folders contained in the synchronized folder.
104 */
105 public List<OCFile> getChildren() {
106 return mChildren;
107 }
108
109
110 @Override
111 protected RemoteOperationResult run(WebdavClient client) {
112 RemoteOperationResult result = null;
113 mFailsInFavouritesFound = 0;
114 mConflictsFound = 0;
115
116 // code before in FileSyncAdapter.fetchData
117 PropFindMethod query = null;
118 try {
119 Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
120
121 // remote request
122 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
123 int status = client.executeMethod(query);
124
125 // check and process response - /// TODO take into account all the possible status per child-resource
126 if (isMultiStatus(status)) {
127 MultiStatus resp = query.getResponseBodyAsMultiStatus();
128
129 // synchronize properties of the parent folder, if necessary
130 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
131 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
132 OCFile parent = fillOCFile(we);
133 mStorageManager.saveFile(parent);
134 mParentId = parent.getFileId();
135 }
136
137 // read contents in folder
138 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
139 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
140 for (int i = 1; i < resp.getResponses().length; ++i) {
141 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
142 OCFile file = fillOCFile(we);
143 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
144 if (oldFile != null) {
145 file.setKeepInSync(oldFile.keepInSync());
146 file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
147 if (file.keepInSync()) {
148 //disableObservance(file); // first disable observer so we won't get file upload right after download
149 // // now, the FileDownloader service sends a broadcast before start a download; the FileObserverService is listening for it
150 //requestFileSynchronization(file, oldFile, client);
151 SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
152 file,
153 mStorageManager,
154 mAccount,
155 true,
156 false,
157 mContext
158 );
159 filesToSyncContents.add(operation);
160 }
161 }
162
163 updatedFiles.add(file);
164 }
165
166 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
167 mStorageManager.saveFiles(updatedFiles);
168
169 // request for the synchronization of files AFTER saving last properties
170 SynchronizeFileOperation op = null;
171 RemoteOperationResult contentsResult = null;
172 for (int i=0; i < filesToSyncContents.size(); i++) {
173 op = filesToSyncContents.get(i);
174 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
175 if (!contentsResult.isSuccess()) {
176 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
177 mConflictsFound++;
178 } else {
179 mFailsInFavouritesFound++;
180 if (contentsResult.getException() != null) {
181 Log.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
182 } else {
183 Log.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
184 }
185 }
186 } // won't let these fails break the synchronization process
187 }
188
189
190 // removal of obsolete files
191 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
192 OCFile file;
193 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
194 for (int i=0; i < mChildren.size(); ) {
195 file = mChildren.get(i);
196 if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
197 Log.d(TAG, "removing file: " + file);
198 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
199 mChildren.remove(i);
200 } else {
201 i++;
202 }
203 }
204
205 } else {
206 client.exhaustResponse(query.getResponseBodyAsStream());
207 }
208
209 // prepare result object
210 if (isMultiStatus(status)) {
211 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
212 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
213
214 } else {
215 result = new RemoteOperationResult(true, status);
216 }
217 } else {
218 result = new RemoteOperationResult(false, status);
219 }
220 Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
221
222
223 } catch (Exception e) {
224 result = new RemoteOperationResult(e);
225 Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
226
227 } finally {
228 if (query != null)
229 query.releaseConnection(); // let the connection available for other methods
230 }
231
232 return result;
233 }
234
235
236 public boolean isMultiStatus(int status) {
237 return (status == HttpStatus.SC_MULTI_STATUS);
238 }
239
240
241 /**
242 * Creates and populates a new {@link OCFile} object with the data read from the server.
243 *
244 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
245 * @return New OCFile instance representing the remote resource described by we.
246 */
247 private OCFile fillOCFile(WebdavEntry we) {
248 OCFile file = new OCFile(we.decodedPath());
249 file.setCreationTimestamp(we.createTimestamp());
250 file.setFileLength(we.contentLength());
251 file.setMimetype(we.contentType());
252 file.setModificationTimestamp(we.modifiedTimesamp());
253 file.setLastSyncDateForProperties(mCurrentSyncTime);
254 file.setParentId(mParentId);
255 return file;
256 }
257
258
259 }