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