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