Download button in file details view upgraded to sync file content 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.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 import com.owncloud.android.files.services.FileObserverService;
37 import com.owncloud.android.utils.FileStorageUtils;
38
39 import eu.alefzero.webdav.WebdavClient;
40 import eu.alefzero.webdav.WebdavEntry;
41 import eu.alefzero.webdav.WebdavUtils;
42
43
44 /**
45 * Remote operation performing the synchronization a the contents of a remote folder with the local database
46 *
47 * @author David A. Velasco
48 */
49 public class SynchronizeFolderOperation extends RemoteOperation {
50
51 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
52
53 /** Remote folder to synchronize */
54 private String mRemotePath;
55
56 /** Timestamp for the synchronization in progress */
57 private long mCurrentSyncTime;
58
59 /** Id of the folder to synchronize in the local database */
60 private long mParentId;
61
62 /** Access to the local database */
63 private DataStorageManager mStorageManager;
64
65 /** Account where the file to synchronize belongs */
66 private Account mAccount;
67
68 /** Android context; necessary to send requests to the download service; maybe something to refactor */
69 private Context mContext;
70
71 /** Files and folders contained in the synchronized folder */
72 private List<OCFile> mChildren;
73
74
75 public SynchronizeFolderOperation( String remotePath,
76 long currentSyncTime,
77 long parentId,
78 DataStorageManager dataStorageManager,
79 Account account,
80 Context context ) {
81 mRemotePath = remotePath;
82 mCurrentSyncTime = currentSyncTime;
83 mParentId = parentId;
84 mStorageManager = dataStorageManager;
85 mAccount = account;
86 mContext = context;
87 }
88
89
90 /**
91 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
92 *
93 * @return List of files and folders contained in the synchronized folder.
94 */
95 public List<OCFile> getChildren() {
96 return mChildren;
97 }
98
99
100 @Override
101 protected RemoteOperationResult run(WebdavClient client) {
102 RemoteOperationResult result = null;
103
104 // code before in FileSyncAdapter.fetchData
105 PropFindMethod query = null;
106 try {
107 Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
108
109 // remote request
110 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
111 int status = client.executeMethod(query);
112
113 // check and process response - /// TODO take into account all the possible status per child-resource
114 if (isMultiStatus(status)) {
115 MultiStatus resp = query.getResponseBodyAsMultiStatus();
116
117 // synchronize properties of the parent folder, if necessary
118 if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
119 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
120 OCFile parent = fillOCFile(we);
121 parent.setParentId(mParentId);
122 mStorageManager.saveFile(parent);
123 mParentId = parent.getFileId();
124 }
125
126 // read contents in folder
127 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
128 for (int i = 1; i < resp.getResponses().length; ++i) {
129 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
130 OCFile file = fillOCFile(we);
131 file.setParentId(mParentId);
132 OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
133 if (oldFile != null) {
134 if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) {
135 disableObservance(file); // first disable observer so we won't get file upload right after download
136 requestContentDownload(file);
137 }
138 file.setKeepInSync(oldFile.keepInSync());
139 }
140
141 updatedFiles.add(file);
142 }
143
144 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
145 mStorageManager.saveFiles(updatedFiles);
146
147
148 // removal of obsolete files
149 mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
150 OCFile file;
151 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
152 for (int i=0; i < mChildren.size(); ) {
153 file = mChildren.get(i);
154 if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
155 Log.d(TAG, "removing file: " + file);
156 mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
157 mChildren.remove(i);
158 } else {
159 i++;
160 }
161 }
162
163 } else {
164 client.exhaustResponse(query.getResponseBodyAsStream());
165 }
166
167 // prepare result object
168 result = new RemoteOperationResult(isMultiStatus(status), status);
169 Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
170
171
172 } catch (Exception e) {
173 result = new RemoteOperationResult(e);
174 Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
175
176 } finally {
177 if (query != null)
178 query.releaseConnection(); // let the connection available for other methods
179 }
180
181 return result;
182 }
183
184
185 public boolean isMultiStatus(int status) {
186 return (status == HttpStatus.SC_MULTI_STATUS);
187 }
188
189
190 /**
191 * Creates and populates a new {@link OCFile} object with the data read from the server.
192 *
193 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
194 * @return New OCFile instance representing the remote resource described by we.
195 */
196 private OCFile fillOCFile(WebdavEntry we) {
197 OCFile file = new OCFile(we.decodedPath());
198 file.setCreationTimestamp(we.createTimestamp());
199 file.setFileLength(we.contentLength());
200 file.setMimetype(we.contentType());
201 file.setModificationTimestamp(we.modifiedTimesamp());
202 file.setLastSyncDateForProperties(mCurrentSyncTime);
203 return file;
204 }
205
206
207 /**
208 * Request to stop the observance of local updates for a file.
209 *
210 * @param file OCFile representing the remote file to stop to monitor for local updates
211 */
212 private void disableObservance(OCFile file) {
213 Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
214 Intent intent = new Intent(mContext, FileObserverService.class);
215 intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
216 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, file);
217 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
218 mContext.startService(intent);
219
220 }
221
222
223 /**
224 * Requests a download to the file download service
225 *
226 * @param file OCFile representing the remote file to download
227 */
228 private void requestContentDownload(OCFile file) {
229 Intent intent = new Intent(mContext, FileDownloader.class);
230 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
231 intent.putExtra(FileDownloader.EXTRA_FILE, file);
232 mContext.startService(intent);
233 }
234
235
236 }