Merge branch 'develop' into setup_buttons
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFileOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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 org.apache.http.HttpStatus;
22 import org.apache.jackrabbit.webdav.DavConstants;
23 import org.apache.jackrabbit.webdav.MultiStatus;
24 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
25
26 import com.owncloud.android.Log_OC;
27 import com.owncloud.android.datamodel.FileDataStorageManager;
28 import com.owncloud.android.datamodel.OCFile;
29 import com.owncloud.android.files.services.FileDownloader;
30 import com.owncloud.android.files.services.FileUploader;
31 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
32
33 import android.accounts.Account;
34 import android.content.Context;
35 import android.content.Intent;
36
37
38 import eu.alefzero.webdav.WebdavClient;
39 import eu.alefzero.webdav.WebdavEntry;
40 import eu.alefzero.webdav.WebdavUtils;
41
42 public class SynchronizeFileOperation extends RemoteOperation {
43
44 private String TAG = SynchronizeFileOperation.class.getSimpleName();
45 private static final int SYNC_READ_TIMEOUT = 10000;
46 private static final int SYNC_CONNECTION_TIMEOUT = 5000;
47
48 private OCFile mLocalFile;
49 private OCFile mServerFile;
50 private FileDataStorageManager mStorageManager;
51 private Account mAccount;
52 private boolean mSyncFileContents;
53 private Context mContext;
54
55 private boolean mTransferWasRequested = false;
56
57 public SynchronizeFileOperation(
58 OCFile localFile,
59 OCFile serverFile, // make this null to let the operation checks the server; added to reuse info from SynchronizeFolderOperation
60 FileDataStorageManager storageManager,
61 Account account,
62 boolean syncFileContents,
63 Context context) {
64
65 mLocalFile = localFile;
66 mServerFile = serverFile;
67 mStorageManager = storageManager;
68 mAccount = account;
69 mSyncFileContents = syncFileContents;
70 mContext = context;
71 }
72
73
74 @Override
75 protected RemoteOperationResult run(WebdavClient client) {
76
77 PropFindMethod propfind = null;
78 RemoteOperationResult result = null;
79 mTransferWasRequested = false;
80 try {
81 if (!mLocalFile.isDown()) {
82 /// easy decision
83 requestForDownload(mLocalFile);
84 result = new RemoteOperationResult(ResultCode.OK);
85
86 } else {
87 /// local copy in the device -> need to think a bit more before do anything
88
89 if (mServerFile == null) {
90 /// take the duty of check the server for the current state of the file there
91 propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mLocalFile.getRemotePath()),
92 DavConstants.PROPFIND_ALL_PROP,
93 DavConstants.DEPTH_0);
94 int status = client.executeMethod(propfind, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);
95 boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS;
96 if (isMultiStatus) {
97 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
98 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
99 client.getBaseUri().getPath());
100 mServerFile = fillOCFile(we);
101 mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
102
103 } else {
104 client.exhaustResponse(propfind.getResponseBodyAsStream());
105 result = new RemoteOperationResult(false, status, propfind.getResponseHeaders());
106 }
107 }
108
109 if (result == null) { // true if the server was not checked. nothing was wrong with the remote request
110
111 /// check changes in server and local file
112 boolean serverChanged = false;
113 /* time for eTag is coming, but not yet
114 if (mServerFile.getEtag() != null) {
115 serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag())); // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
116 } else { */
117 // server without etags
118 serverChanged = (mServerFile.getModificationTimestamp() > mLocalFile.getModificationTimestampAtLastSyncForData());
119 //}
120 boolean localChanged = (mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
121 // TODO this will be always true after the app is upgraded to database version 2; will result in unnecessary uploads
122
123 /// decide action to perform depending upon changes
124 //if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
125 if (localChanged && serverChanged) {
126 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
127
128 } else if (localChanged) {
129 if (mSyncFileContents) {
130 requestForUpload(mLocalFile);
131 // the local update of file properties will be done by the FileUploader service when the upload finishes
132 } else {
133 // NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
134 // So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
135 // that an upload is necessary (for instance, in FileObserverService).
136 }
137 result = new RemoteOperationResult(ResultCode.OK);
138
139 } else if (serverChanged) {
140 if (mSyncFileContents) {
141 requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
142 // the update of local data will be done later by the FileUploader service when the upload finishes
143 } else {
144 // TODO CHECK: is this really useful in some point in the code?
145 mServerFile.setKeepInSync(mLocalFile.keepInSync());
146 mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
147 mServerFile.setStoragePath(mLocalFile.getStoragePath());
148 mServerFile.setParentId(mLocalFile.getParentId());
149 mStorageManager.saveFile(mServerFile);
150
151 }
152 result = new RemoteOperationResult(ResultCode.OK);
153
154 } else {
155 // nothing changed, nothing to do
156 result = new RemoteOperationResult(ResultCode.OK);
157 }
158
159 }
160
161 }
162
163 Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
164
165 } catch (Exception e) {
166 result = new RemoteOperationResult(e);
167 Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", file " + (mLocalFile != null ? mLocalFile.getRemotePath() : "NULL") + ": " + result.getLogMessage(), result.getException());
168
169 } finally {
170 if (propfind != null)
171 propfind.releaseConnection();
172 }
173 return result;
174 }
175
176
177 /**
178 * Requests for an upload to the FileUploader service
179 *
180 * @param file OCFile object representing the file to upload
181 */
182 private void requestForUpload(OCFile file) {
183 Intent i = new Intent(mContext, FileUploader.class);
184 i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
185 i.putExtra(FileUploader.KEY_FILE, file);
186 /*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it!
187 i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
188 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
189 i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
190 mContext.startService(i);
191 mTransferWasRequested = true;
192 }
193
194
195 /**
196 * Requests for a download to the FileDownloader service
197 *
198 * @param file OCFile object representing the file to download
199 */
200 private void requestForDownload(OCFile file) {
201 Intent i = new Intent(mContext, FileDownloader.class);
202 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
203 i.putExtra(FileDownloader.EXTRA_FILE, file);
204 mContext.startService(i);
205 mTransferWasRequested = true;
206 }
207
208
209 /**
210 * Creates and populates a new {@link OCFile} object with the data read from the server.
211 *
212 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
213 * @return New OCFile instance representing the remote resource described by we.
214 */
215 private OCFile fillOCFile(WebdavEntry we) {
216 OCFile file = new OCFile(we.decodedPath());
217 file.setCreationTimestamp(we.createTimestamp());
218 file.setFileLength(we.contentLength());
219 file.setMimetype(we.contentType());
220 file.setModificationTimestamp(we.modifiedTimestamp());
221 file.setEtag(we.etag());
222
223 return file;
224 }
225
226
227 public boolean transferWasRequested() {
228 return mTransferWasRequested;
229 }
230
231
232 public OCFile getLocalFile() {
233 return mLocalFile;
234 }
235
236 }