Removed more code and string about unused location tracking
[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.DavConstants;
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
39 import com.owncloud.android.Log_OC;
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_OC.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
136
137 // remote request
138 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath),
139 DavConstants.PROPFIND_ALL_PROP,
140 DavConstants.DEPTH_1);
141 int status = client.executeMethod(query);
142
143 // check and process response - /// TODO take into account all the possible status per child-resource
144 if (isMultiStatus(status)) {
145 MultiStatus resp = query.getResponseBodyAsMultiStatus();
146
147 // synchronize properties of the parent folder, if necessary
148 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
149 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
150 OCFile parent = fillOCFile(we);
151 mStorageManager.saveFile(parent);
152 mParentId = parent.getFileId();
153 }
154
155 // read contents in folder
156 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
157 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
158 for (int i = 1; i < resp.getResponses().length; ++i) {
159 /// new OCFile instance with the data from the server
160 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
161 OCFile file = fillOCFile(we);
162
163 /// set data about local state, keeping unchanged former data if existing
164 file.setLastSyncDateForProperties(mCurrentSyncTime);
165 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
166 if (oldFile != null) {
167 file.setKeepInSync(oldFile.keepInSync());
168 file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
169 file.setModificationTimestampAtLastSyncForData(oldFile.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
170 checkAndFixForeignStoragePath(oldFile);
171 file.setStoragePath(oldFile.getStoragePath());
172 }
173
174 /// scan default location if local copy of file is not linked in OCFile instance
175 if (file.getStoragePath() == null && !file.isDirectory()) {
176 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
177 if (f.exists()) {
178 file.setStoragePath(f.getAbsolutePath());
179 file.setLastSyncDateForData(f.lastModified());
180 }
181 }
182
183 /// prepare content synchronization for kept-in-sync files
184 if (file.keepInSync()) {
185 SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
186 file,
187 mStorageManager,
188 mAccount,
189 true,
190 false,
191 mContext
192 );
193 filesToSyncContents.add(operation);
194 }
195
196 updatedFiles.add(file);
197 }
198
199 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
200 mStorageManager.saveFiles(updatedFiles);
201
202 // request for the synchronization of files AFTER saving last properties
203 SynchronizeFileOperation op = null;
204 RemoteOperationResult contentsResult = null;
205 for (int i=0; i < filesToSyncContents.size(); i++) {
206 op = filesToSyncContents.get(i);
207 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
208 if (!contentsResult.isSuccess()) {
209 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
210 mConflictsFound++;
211 } else {
212 mFailsInFavouritesFound++;
213 if (contentsResult.getException() != null) {
214 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
215 } else {
216 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
217 }
218 }
219 } // won't let these fails break the synchronization process
220 }
221
222
223 // removal of obsolete files
224 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
225 OCFile file;
226 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
227 for (int i=0; i < mChildren.size(); ) {
228 file = mChildren.get(i);
229 if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
230 Log_OC.d(TAG, "removing file: " + file);
231 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
232 mChildren.remove(i);
233 } else {
234 i++;
235 }
236 }
237
238 } else {
239 client.exhaustResponse(query.getResponseBodyAsStream());
240 }
241
242 // prepare result object
243 if (isMultiStatus(status)) {
244 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
245 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
246
247 } else {
248 result = new RemoteOperationResult(true, status, query.getResponseHeaders());
249 }
250 } else {
251 result = new RemoteOperationResult(false, status, query.getResponseHeaders());
252 }
253
254
255
256 } catch (Exception e) {
257 result = new RemoteOperationResult(e);
258
259
260 } finally {
261 if (query != null)
262 query.releaseConnection(); // let the connection available for other methods
263 if (result.isSuccess()) {
264 Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
265 } else {
266 if (result.isException()) {
267 Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
268 } else {
269 Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
270 }
271 }
272 }
273
274 return result;
275 }
276
277
278 public boolean isMultiStatus(int status) {
279 return (status == HttpStatus.SC_MULTI_STATUS);
280 }
281
282
283 /**
284 * Creates and populates a new {@link OCFile} object with the data read from the server.
285 *
286 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
287 * @return New OCFile instance representing the remote resource described by we.
288 */
289 private OCFile fillOCFile(WebdavEntry we) {
290 OCFile file = new OCFile(we.decodedPath());
291 file.setCreationTimestamp(we.createTimestamp());
292 file.setFileLength(we.contentLength());
293 file.setMimetype(we.contentType());
294 file.setModificationTimestamp(we.modifiedTimestamp());
295 file.setParentId(mParentId);
296 return file;
297 }
298
299
300 /**
301 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
302 * tries to copy the file inside it.
303 *
304 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
305 * {@link #mForgottenLocalFiles}
306 *
307 * @param file File to check and fix.
308 */
309 private void checkAndFixForeignStoragePath(OCFile file) {
310 String storagePath = file.getStoragePath();
311 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
312 if (storagePath != null && !storagePath.equals(expectedPath)) {
313 /// fix storagePaths out of the local ownCloud folder
314 File originalFile = new File(storagePath);
315 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
316 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
317 file.setStoragePath(null);
318
319 } else {
320 InputStream in = null;
321 OutputStream out = null;
322 try {
323 File expectedFile = new File(expectedPath);
324 File expectedParent = expectedFile.getParentFile();
325 expectedParent.mkdirs();
326 if (!expectedParent.isDirectory()) {
327 throw new IOException("Unexpected error: parent directory could not be created");
328 }
329 expectedFile.createNewFile();
330 if (!expectedFile.isFile()) {
331 throw new IOException("Unexpected error: target file could not be created");
332 }
333 in = new FileInputStream(originalFile);
334 out = new FileOutputStream(expectedFile);
335 byte[] buf = new byte[1024];
336 int len;
337 while ((len = in.read(buf)) > 0){
338 out.write(buf, 0, len);
339 }
340 file.setStoragePath(expectedPath);
341
342 } catch (Exception e) {
343 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
344 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
345 file.setStoragePath(null);
346
347 } finally {
348 try {
349 if (in != null) in.close();
350 } catch (Exception e) {
351 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
352 }
353 try {
354 if (out != null) out.close();
355 } catch (Exception e) {
356 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
357 }
358 }
359 }
360 }
361 }
362
363
364 }