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