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