Changed the synchronization process to limit the number and type of failures supporte...
[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.content.Intent;
31 import android.util.Log;
32
33 import com.owncloud.android.datamodel.DataStorageManager;
34 import com.owncloud.android.datamodel.OCFile;
35 import com.owncloud.android.files.services.FileDownloader;
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.getCanonicalName();
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
73 public SynchronizeFolderOperation( String remotePath,
74 long currentSyncTime,
75 long parentId,
76 DataStorageManager dataStorageManager,
77 Account account,
78 Context context ) {
79 mRemotePath = remotePath;
80 mCurrentSyncTime = currentSyncTime;
81 mParentId = parentId;
82 mStorageManager = dataStorageManager;
83 mAccount = account;
84 mContext = context;
85 }
86
87
88 /**
89 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
90 *
91 * @return List of files and folders contained in the synchronized folder.
92 */
93 public List<OCFile> getChildren() {
94 return mChildren;
95 }
96
97
98 @Override
99 protected RemoteOperationResult run(WebdavClient client) {
100 RemoteOperationResult result = null;
101
102 // code before in FileSyncAdapter.fetchData
103 PropFindMethod query = null;
104 try {
105 Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
106
107 // remote request
108 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
109 int status = client.executeMethod(query);
110
111 // check and process response - /// TODO take into account all the possible status per child-resource
112 if (isMultiStatus(status)) {
113 MultiStatus resp = query.getResponseBodyAsMultiStatus();
114
115 // synchronize properties of the parent folder, if necessary
116 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
117 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
118 OCFile parent = fillOCFile(we);
119 parent.setParentId(mParentId);
120 mStorageManager.saveFile(parent);
121 mParentId = parent.getFileId();
122 }
123
124 // read contents in folder
125 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
126 for (int i = 1; i < resp.getResponses().length; ++i) {
127 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
128 OCFile file = fillOCFile(we);
129 file.setParentId(mParentId);
130 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
131 if (oldFile != null) {
132 if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) {
133 requestContentDownload(file);
134 }
135 file.setKeepInSync(oldFile.keepInSync());
136 }
137
138 updatedFiles.add(file);
139 }
140
141
142 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
143 mStorageManager.saveFiles(updatedFiles);
144
145
146 // removal of obsolete files
147 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
148 OCFile file;
149 String currentSavePath = FileDownloader.getSavePath(mAccount.name);
150 for (int i=0; i < mChildren.size(); ) {
151 file = mChildren.get(i);
152 if (file.getLastSyncDate() != mCurrentSyncTime) {
153 Log.d(TAG, "removing file: " + file);
154 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
155 mChildren.remove(i);
156 } else {
157 i++;
158 }
159 }
160
161 } else {
162 client.exhaustResponse(query.getResponseBodyAsStream());
163 }
164
165 // prepare result object
166 result = new RemoteOperationResult(isMultiStatus(status), status);
167 Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
168
169
170 } catch (Exception e) {
171 result = new RemoteOperationResult(e);
172 Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
173
174 } finally {
175 if (query != null)
176 query.releaseConnection(); // let the connection available for other methods
177 }
178
179 return result;
180 }
181
182
183 public boolean isMultiStatus(int status) {
184 return (status == HttpStatus.SC_MULTI_STATUS);
185 }
186
187
188 /**
189 * Creates and populates a new {@link OCFile} object with the data read from the server.
190 *
191 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
192 * @return New OCFile instance representing the remote resource described by we.
193 */
194 private OCFile fillOCFile(WebdavEntry we) {
195 OCFile file = new OCFile(we.decodedPath());
196 file.setCreationTimestamp(we.createTimestamp());
197 file.setFileLength(we.contentLength());
198 file.setMimetype(we.contentType());
199 file.setModificationTimestamp(we.modifiedTimesamp());
200 file.setLastSyncDate(mCurrentSyncTime);
201 return file;
202 }
203
204
205 /**
206 * Requests a download to the file download service
207 *
208 * @param file OCFile representing the remote file to download
209 */
210 private void requestContentDownload(OCFile file) {
211 Intent intent = new Intent(mContext, FileDownloader.class);
212 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
213 intent.putExtra(FileDownloader.EXTRA_FILE, file);
214 mContext.startService(intent);
215 }
216
217
218 }